use*_*307 5 javascript arrays spread-syntax
我正在根据此处解释的条件将元素推送到数组http://2ality.com/2017/04/conditional-literal-entries.html
const arr = [
...(cond ? ['a'] : []),
'b',
];
Run Code Online (Sandbox Code Playgroud)
现在,这很好用,但是当我尝试时
const arr = [
...(cond && ['a']),
'b',
];
Run Code Online (Sandbox Code Playgroud)
相反,它停止工作。
我想知道为什么它不再起作用,以及是否有办法使用扩展运算符和 && 而不是 ? 有条件地推送。
谢谢
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
The built-in types with a @@iterator method are:
var cond = false;
const arr = [
...(cond && ['a']), // throws error, function expected
'b',
];
console.log(arr);Run Code Online (Sandbox Code Playgroud)
是的,这是可能的。但也许这是一种矫枉过正,性能更差并降低可读性。
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);Run Code Online (Sandbox Code Playgroud)
正如@Nina Scholz指出的,扩展运算符需要一个迭代器才能工作。通过使用第二个数组(可能为空),我们最终可以达到以下状态 ( arr.push())。