在JavaScript中有条件地在Array中添加元素 [英] Add elements inside Array conditionally in JavaScript

查看:104
本文介绍了在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'};

当我尝试对数组使用相同的逻辑时,它仅在条件为<$ c时有效$ c> 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 对象

推荐答案

当你传播到 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.

这篇关于在JavaScript中有条件地在Array中添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆