This question already has an answer here:
这个问题在这里已有答案:
- How to use a variable for a key in a JavaScript object literal? 7 answers
- 如何在JavaScript对象文字中使用变量作为键? 7个答案
var elems = [];
var at1 = $(indx).attr('class'); //or any string
var at2 = $(indx).html(); //or any string
elems.push({
at1: at2
});
The output I get is: this Why can not I set the key as a string?
我得到的输出是:这为什么我不能将密钥设置为字符串?
1 个解决方案
#1
4
The way you create an object, the key is going to be interpreted literally as "at1"
string. In your case you need to do it slightly more verbose:
创建对象的方式,键将被解释为字形“at1”字符串。在你的情况下,你需要更详细一点:
var at1 = $(indx).attr('class');
var at2 = $(indx).html();
var obj = {};
obj[at1] = at2;
elems.push(obj);
... or using ES2015 computed property name:
...或使用ES2015计算属性名称:
var at1 = $(indx).attr('class');
var at2 = $(indx).html();
elems.push({
[at1]: at2
});
#1
4
The way you create an object, the key is going to be interpreted literally as "at1"
string. In your case you need to do it slightly more verbose:
创建对象的方式,键将被解释为字形“at1”字符串。在你的情况下,你需要更详细一点:
var at1 = $(indx).attr('class');
var at2 = $(indx).html();
var obj = {};
obj[at1] = at2;
elems.push(obj);
... or using ES2015 computed property name:
...或使用ES2015计算属性名称:
var at1 = $(indx).attr('class');
var at2 = $(indx).html();
elems.push({
[at1]: at2
});