我这样定义一个数组:
[{foo:0}, true === false && { foobar:1}, {bar:2}]
我的预期结果是当不满足中间条件时根本不添加中间项:
[ { foo: 0 }, { bar: 2 } ]
事实上它添加了 false 作为数组项:
[ { foo: 0 }, false, { bar: 2 } ]
有没有办法在保持这种轻量级语法的同时防止添加 false
(我知道我总是可以使用 push 或传播运算符)
最佳答案
您可以使用带有扩展语法的 concat
和一个空数组作为中性值。
var a = [].concat(...[
{ foo: 0 },
true === false ? { foobar: 1 } : [],
{ bar: 2 }
]);
console.log(a);
应用
var a = Array.prototype.concat.apply([], [
{ foo: 0 },
true === false ? { foobar: 1 } : [],
{ bar: 2 }
]);
console.log(a);
关于javascript - 根据条件在定义时添加数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49302745/