在JavaScript中有条件地在Array中添加元素

问题描述:

当我尝试有条件地使用spread运算符合并两个对象时,它在条件为 true false 时有效>:

When I try to merge two objects using the spread operator conditionally, it works when the condition is true or false:

let condition = false;
let obj1 = { key1: 'value1'}
let obj2 = {
  key2: 'value2',
  ...(condition && obj1),
};

// obj2 = {key2: 'value2'};

当我尝试对数组使用相同的逻辑时,它仅在条件为 true :

When I try to use the same logic with Arrays, it only works when the condition is true:

let condition = true;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// arr2 = ['value2', 'value1']

如果条件是 false 则抛出错误:

If the condition is false an error is thrown:

let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition && arr1)];

// Error

为什么 Array $ c之间的行为不同$ c>和对象

当你传播到 array ,在对象上调用 Symbol.iterator 方法。 && 评估为第一个假值(或最后一个真值,如果所有都是真的),所以

When you spread into an array, you call the Symbol.iterator method on the object. && evaluates to the first falsey value (or the last truthy value, if all are truthy), so

let arr2 = ['value2', ...(condition && arr)];

结果

let arr2 = ['value2', ...(false)];

false 没有 Symbol.iterator 方法。

您可以使用条件运算符,如果条件为false,则传播空数组:

You could use the conditional operator instead, and spread an empty array if the condition is false:

let condition = false;
let arr1 = ['value1'];
let arr2 = ['value2', ...(condition ? arr1 : [])];
console.log(arr2);

(这是因为空数组 具有 Symbol.iterator 方法)

(This works because the empty array does have the Symbol.iterator method)

对象传播完全不同:它将自己的可枚举属性从提供的对象复制到新对象上。 false 没有任何自己的可枚举属性,因此不会复制任何内容。

Object spread is completely different: it copies own enumerable properties from a provided object onto a new object. false does not have any own enumerable properties, so nothing gets copied.