[英]'Unexpected token d' when trying to add objects to a Javascript Object array
我在hotKeyService
有一个空对象,如下所示:
{hotKeys: [
]
}
我想向该数组中添加对象的负载,以给出以下形式的最终结果:
{hotKeys: [
"demoBtn1":{
keyCode: 49,
keyShortcut: "1",
label: "button"
},
"demoBtn2":{
keyCode: 50,
keyShortcut: "2",
label: "button"
},
]
}
目前,我的代码是:
hotKeyService.hotKeys.push(attrs.id);
var arrayRow = hotKeyService.hotKeys.length - 1;
var currentObj = JSON.parse(hotKeyService.hotKeys[arrayRow]);
currentObj.keyCode = attrs.keyCode;
currentObj.keyShortcut = attrs.keyShortcut;
currentObj.label = attrs.label;
在尝试为currentObj
解析JSON的点上,我收到了错误。 如果我不解析Cannot assign to read only property 'keyCode' of demoBtn1
得到Cannot assign to read only property 'keyCode' of demoBtn1
错误的Cannot assign to read only property 'keyCode' of demoBtn1
,这是因为对象需要解析。
如何按预期填充对象?
谢谢
数组没有“键”(它们有属性,但这是不可能的)。 我相信您想使用{}
代替[]
。
数组由值列表组成:
[ foo, bar, baz ]
不是一系列键:值对(用于对象):
{ a: foo, b: bar, c: baz }
数组中的值当然可以是对象:
[ { foo: {} }, { bar: {} }, { baz: {} } ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.