Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用户输入对象属性和键_Javascript_Html - Fatal编程技术网

Javascript 如何使用户输入对象属性和键

Javascript 如何使用户输入对象属性和键,javascript,html,Javascript,Html,我手上有一个非常罕见的问题。我需要用户输入对象的键和属性 我有一个输入 <input type="text"> <input type="button" value="enter"> 有办法做到这一点吗? 谢谢您需要使用括号表示法: 如果将输入存储在名为input的变量中,则应执行以下操作: var myObj = {}; obj[input] = input; 像这样的 HTML: <input type="text" id="yourInput">

我手上有一个非常罕见的问题。我需要用户输入对象的键和属性

我有一个
输入

<input type="text">
<input type="button" value="enter">
有办法做到这一点吗?

谢谢

您需要使用括号表示法:

如果将输入存储在名为input的变量中,则应执行以下操作:

var myObj = {};
obj[input] = input;
像这样的

HTML:

<input type="text" id="yourInput">
<input type="button" value="Enter" id="enterBtn">
var obj = {},
    enterBtn = document.getElementById('enterBtn'),
    yourInput = document.getElementById('yourInput');

enterBtn.onclick = function () {
    var input = yourInput.value;
    // Don't add anything to the obj if the input is empty.
    if(!input) return;
    // Use brackets to add a property to the obj, and set the value to be the same
    // as the property name.
    obj[input] = input;
    console.log(obj);
};

有没有办法用文字符号来表达呢?不,我不知道。是的,谢谢,这是我最初的问题,但我被提醒我的问题没有被很好地理解。所以我改了。很抱歉
var obj = {},
    enterBtn = document.getElementById('enterBtn'),
    yourInput = document.getElementById('yourInput');

enterBtn.onclick = function () {
    var input = yourInput.value;
    // Don't add anything to the obj if the input is empty.
    if(!input) return;
    // Use brackets to add a property to the obj, and set the value to be the same
    // as the property name.
    obj[input] = input;
    console.log(obj);
};