使用数组属性初始化对象

Initialise an object with array properties

如何初始化 JavaScript 中的对象,其属性是数组?

我想要一个这种格式的对象:

foo = { prop1: [0, 1], prop2: [1, 1], prop3: [0] }

我的用例如下:

-当属性不存在时,创建这个属性,应该是一个数组,并添加一个数字。

- 当 属性 已经存在时,将数字推送到该数组;这样我就不能每次都初始化一个数组了。

到目前为止我所做的是:

  var obj = {};
  arr.forEach(x => { !obj[x] && obj[x].push(1) });

我收到这个错误:

Uncaught TypeError: Cannot read property 'push' of undefined

这是有道理的,因为 属性 尚未初始化为空数组。

添加此代码段:

arr.forEach((x) => {obj[x] = (obj[x] || []).concat(1);})

如果obj[x]undefined,那么它还没有被初始化。因此,undefined || [] 解析为 [],一个空数组,1 或您想要的任何数据都可以连接到该数组。

再见,你可以试试这个:

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);

if obj 已经 属性 x (hasOwnProperty) push value 1 else init x as array 属性 and push 1.