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);
};