借助OR运算符||将数组添加到对象

问题描述

我想向数组添加一些值,该数组是对象的一部分。

  • 如果键值已存在于对象中:推至数组的末尾
  • 其他:创建数组

此作品有效:

let objectWithArr = {};
const key = "Words";

function increaseCount(key,value) {
  if (typeof (objectWithArr[key]) === "undefined") objectWithArr[key] = [value];
  else objectWithArr[key].push(value);
}

increaseCount(key,"Entry 1");
console.log(objectWithArr);
increaseCount(key,"Entry 2");
console.log(objectWithArr);

但是这个不起作用:

let objectWithArr = {};
const key = "Words";

function increaseCount(key,value) {
  objectWithArr[key] = objectWithArr[key].push(value) || [value];
}

increaseCount(key,"Entry 2");
console.log(objectWithArr);

想知道为什么第二版失败了。有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)