问题描述
如何在JavaScript中初始化其属性为数组的对象?
我想要一个这种格式的对象:
foo = { prop1: [0,1],prop2: [1,prop3: [0] }
我的用例如下:
-当属性已经存在时,将数字压入该数组;这样,我无法每次都初始化数组。
到目前为止,我所做的是:
var obj = {};
arr.forEach(x => { !obj[x] && obj[x].push(1) });
我收到此错误:
未捕获的TypeError:无法读取未定义的属性“ push”
这很有意义,因为该属性尚未初始化为空数组。
解决方法
添加此代码段:
arr.forEach((x) => {obj[x] = (obj[x] || []).concat(1);})
如果obj[x]
是undefined
,则说明尚未初始化。因此,undefined || []
解析为[]
,这是一个空数组,1
或您想要的任何数据都可以连接到该空数组。
请您尝试以下操作:
Picture.Range.InlineShapes.AddPicture FileName:=filetoinsert,LinkToFile:=False,SaveWithDocument:=True
如果obj已经具有属性x(let obj = {};
let arr = ["prop1","prop2","prop1","prop3"];
arr.forEach((x) => {
if(obj.hasOwnProperty(x)) obj[x].push(1);
else {
obj[x] = [];
obj[x].push(1);
}
})
console.log(obj);
)推入值1,则将init x作为数组属性并推入1。