使用扩展运算符有条件地推送到数组
Conditionally pushing to an array with spread operator
我正在根据此处解释的条件将元素推送到数组 http://2ality.com/2017/04/conditional-literal-entries.html
const arr = [
...(cond ? ['a'] : []),
'b',
];
现在,这工作正常,但是当我尝试
const arr = [
...(cond && ['a']),
'b',
];
相反,它停止工作。
我想知道为什么它不再工作了,是否有办法使用扩展运算符和 && 而不是 ? 来有条件地推送。
谢谢
不,这是不可能的,因为所有可迭代对象都是真实的。
如果 cond
是假的,你有一个不能被 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);
是的,有可能。 但也许这有点矫枉过正 性能更差并降低了可读性。
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);
作为@Nina Scholz 传播运算符需要一个可迭代的才能工作。通过使用第二个数组(可能为空)我们最终可以达到以下状态(arr.push()
)。
我正在根据此处解释的条件将元素推送到数组 http://2ality.com/2017/04/conditional-literal-entries.html
const arr = [
...(cond ? ['a'] : []),
'b',
];
现在,这工作正常,但是当我尝试
const arr = [
...(cond && ['a']),
'b',
];
相反,它停止工作。
我想知道为什么它不再工作了,是否有办法使用扩展运算符和 && 而不是 ? 来有条件地推送。
谢谢
不,这是不可能的,因为所有可迭代对象都是真实的。
如果 cond
是假的,你有一个不能被 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);
是的,有可能。 但也许这有点矫枉过正 性能更差并降低了可读性。
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);
作为@Nina Scholz arr.push()
)。