如何定义条件数组元素? 我想这样做:

const cond = true;
const myArr = ["foo", cond && "bar"];

这正如预期的那样工作,结果是["foo", "bar"],但如果我将cond设置为false,我得到以下结果:["foo", false]

如何定义具有条件元素的数组?


当前回答

这是Jordan Enev的答案的替代方案,如果你不太关心性能,感觉你想学习更多关于Javascript的知识:)

如果你想这样做,但是没有false/undefined/null元素

['foo', true && 'bar', null && 'baz']; // ['foo', 'bar', null]

你可以这样做:

['foo', true && 'bar', ...Object.values({ ...(null && ['baz']) })]; // ['foo', 'bar']

最后,正条件将如预期的那样工作:

['foo', true && 'bar', ...Object.values({ ...(true && ['baz']) })]; // ['foo', 'bar', 'baz']

好处:如果你想向数组中添加一个东西,但这个东西可能是假的,然后你不想让它在那里,不做第二次操作,这里有一种方法:

const foo = 1; // 1
const bar = (() => 'expensive result that turns out falsy for bar' && false)(); // false
const baz = (() => 'expensive result for baz')(); // 'expensive result'
const conditionalArrayWrapperFor = i => i ? [i] : [];
// tip: you can always inline conditionalWrapper if you only execute it once
// for instance, if you're using this inside a reduce call
[foo, ...conditionalArrayWrapperFor(bar), ...conditionalArrayWrapperFor(baz)] // [1, 'expensive result for baz']

其他回答

如果你正在使用es6,我会建议

Let array = [ “自行车”, “汽车”, Name === "van" ?"van": null, “公共汽车”, “卡车”, ] .filter(布尔);

如果name = "van",该数组将只包含值"van",否则将被丢弃。

如果你真的想把它作为一行,你可以使用:

const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);

我会这样做

[
  true && 'one',
  false && 'two',
  1 === 1 && 'three',
  1 + 1 === 9 && 'four'
].filter(Boolean) // ['one', 'three']

注意,这也会删除错误的值,比如空字符串。

除了使用push,你没有太多的选择:

const cond = true;
const myArr = ["foo"];

if (cond) myArr.push("bar");

另一个想法是添加null并过滤掉它们:

const cond = true;
const myArr = ["foo", cond ? "bar" : null];

myArr = myArr.filter((item) => item !== null);

你可以试试简单的if:

if(cond) {
    myArr.push("bar");
}