[英]Variable in the object properties name
I want to set object like this: 我想这样设置对象:
var x = 20;
var y = 30;
var z = {
values: {
x: '24',
y: '60' },
value: x
};
I would like the variable z to look: 我希望变量z看起来:
var z = {
values: {
20: '24',
30: '60' },
value: 20
};
Put them in square
bracket. 将它们放在
square
括号中。 This is commonly known as computed property names which allows a variable to put in square bracket which will be computed 这通常称为计算属性名称,它允许将变量放在要计算的方括号中
var x = 20; var y = 30; var z = { values: { [x]: '24', [y]: '60' }, value: x }; console.log(z)
Square bracket solution posted by brk is good, but only under browsers different than Internet Explorer. brk发布的方括号解决方案很好,但只能在与Internet Explorer不同的浏览器中使用。 Under IE11 you need to do something like this:
在IE11下,您需要执行以下操作:
var x = 20;
var y = 30;
var z = {
values: { },
value: x
};
z['values'][String(x)] = '24';
z['values'][String(y)] = '60';
console.log(z);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.