有条件地使用扩展运算符推送到数组

时间:2022-06-07 21:18:16

I am pushing elements to an array based on a condition as explained here http://2ality.com/2017/04/conditional-literal-entries.html

我正在根据这里解释的条件将元素推送到数组中http://2ality.com/2017/04/conditional-literal-entries.html

const arr = [
  ...(cond ? ['a'] : []),
  'b',
];

Now, this works fine, but when I try

现在,这很好,但是当我尝试时

const arr = [
  ...(cond && ['a']),
  'b',
];

instead, it stops working.

相反,它停止工作。

I would like to know why it's not working anymore, and if there is a way to conditionally push using spread operator and && instead of ?.

我想知道为什么它不再工作了,如果有条件推动使用spread运算符和&&而不是?

Thank you

2 个解决方案

#1


2  

No, it is not possible, because all iterable objects are truthy.

不,这是不可能的,因为所有可迭代的对象都是真实的。

If cond is falsey, you have a value which is not spreadable by Symbol.iterator

如果cond为false,则表示您具有Symbol.iterator无法传播的值

The built-in types with a @@iterator method are:

带@@ iterator方法的内置类型是:

var cond = false;

const arr = [
  ...(cond && ['a']),  // throws error, function expected
  'b',
];

console.log(arr);

#2


1  

Yes, it's possible. But maybe that's an overkill that performs worse and decreases the readability.

是的,这是可能的。但也许这是一种过度杀伤,表现更差并降低了可读性。

const arr = [];
arr.push(...[false && 'nope'].filter(v => v));
arr.push(...[true && 'yep'].filter(v => v));
arr.push(...[false && 'no', true && 'yes'].filter(v => v));
    
console.info(arr);

As @Nina Scholz indicated an iterable is required for spread operator to work. By using a second array (which may be empty) we can eventually reach the following state (arr.push()).

正如@Nina Scholz所说,扩展运算符需要迭代才能工作。通过使用第二个数组(可能为空),我们最终可以达到以下状态(arr.push())。

#1


2  

No, it is not possible, because all iterable objects are truthy.

不,这是不可能的,因为所有可迭代的对象都是真实的。

If cond is falsey, you have a value which is not spreadable by Symbol.iterator

如果cond为false,则表示您具有Symbol.iterator无法传播的值

The built-in types with a @@iterator method are:

带@@ iterator方法的内置类型是:

var cond = false;

const arr = [
  ...(cond && ['a']),  // throws error, function expected
  'b',
];

console.log(arr);

#2


1  

Yes, it's possible. But maybe that's an overkill that performs worse and decreases the readability.

是的,这是可能的。但也许这是一种过度杀伤,表现更差并降低了可读性。

const arr = [];
arr.push(...[false && 'nope'].filter(v => v));
arr.push(...[true && 'yep'].filter(v => v));
arr.push(...[false && 'no', true && 'yes'].filter(v => v));
    
console.info(arr);

As @Nina Scholz indicated an iterable is required for spread operator to work. By using a second array (which may be empty) we can eventually reach the following state (arr.push()).

正如@Nina Scholz所说,扩展运算符需要迭代才能工作。通过使用第二个数组(可能为空),我们最终可以达到以下状态(arr.push())。