【发布时间】:2012-02-16 10:03:16
【问题描述】:
这是我试图通过 JavaScript 以点或 [ ] 表示法构建的:
var shoppingCart = {
'item1' : {
'description' : 'This is item #1',
'price' : 10,
'quantity' : 1,
'shipping' : 0,
'total' : 10
}
};
现在如果'item1'是变量名itemName。
这可行:var shoppingCart = {};shoppingCart[itemName] = itemName;alert(shoppingCart.item1);
返回item1
但这不起作用:1 var shoppingCart = {};2 shoppingCart[itemName]['description'] = 'This is Item #1';
JS 在第 2 行就死了,为什么?以及如何将描述值分配给“描述”?
我会这样做:
var shoppingCart = {
itemName : {
'description' : description,
'price' : price,
'quantity' : quantity,
'shipping' : shipping,
'total' : total
}
};
...但它使键字面意思是itemName 而不是item1。
【问题讨论】:
标签: javascript json object assign