如何使用条件元素定义数组?

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


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


它按预期工作:
["foo", "bar"]


但如果我安装
cond


false

, 我会收到以下结果:
["foo", false]


如何使用条件元素定义数组?
已邀请:

风见雨下

赞同来自:

您可以将数组分解在数组中的数组,以使元素的数组保持纯净的条件相等
false

.

这就是你能做的方式

:


// Will result in ['foo', 'bar']
const items = [
'foo',
... true ? ['bar'] : [],
... false ? ['falsy'] : [],
]

console.log/items/



解释

:

正如您所看到的,三元运算符始终返回数组。

如果条件等于
true

, 然后返回
['bar']

, 否则为空数组
[]

.

之后我们宣布
...

结果阵列 /从三元手术开始/, 和数组的元素移动到父数组。

如果数组没有元素 /当热带检查相等时
false

/, 这不会被推出,这是我们的目标。

在另一个答案中,我解释了同样的想法,但是对于物体。 你也可以看看。

.

帅驴

赞同来自:

我会做


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


请注意,它也会删除
https://developer.mozilla.org/ ... Falsy
诸如空行的值。

知食

赞同来自:

你可以尝试简单的话 :


if/cond/ {
myArr.push/"bar"/;
}

涵秋

赞同来自:

如果你

真的

想要将其保存为一个衬垫,可以使用:


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

小明明

赞同来自:

除了使用,您没有许多选项
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/;

君笑尘

赞同来自:

有几种不同的方式,但你怎么会实际工作 Javascript.

最简单的解决方案很容易 if statement.


if /myCond/ arr.push/element/;


还有
filter

, 但我不认为这是你想要的一般,因为你似乎继续 "Add this one thing, if this one condition is true", 并且不要根据某些情况检查一切。 虽然如果你想变得真的打结,你可以做到 /我不推荐,但你可以很酷/.


var arr = ["a", cond && "bar"];
arr.filter/ e => e/


实质上,它只是过滤所有错误的含义。

快网

赞同来自:

const cond = false;
const myArr = ["foo", cond ? "bar" : null].filter/Boolean/;

console.log/myArr/


将导致 ["foo"]

龙天

赞同来自:

替代方法:填充预过滤器而不是后续过滤:


const populate = function/...values/ {
return values.filter/function/el/ {
return el !== false
}/;
};

console.log/populate/"foo", true && "bar", false && "baz"//


回报


/2/ ["foo", "bar"]


我知道它没有解决速记符号 /无论你试过多么努力,它都不会工作/, 但她接近它。

石油百科

赞同来自:

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


let array = [
"bike",
"car",
name === "van" ? "van" : null,
"bus",
"truck",
].filter/Boolean/;


此数组仅包含值。 "van", 如果名称相等 "van", 否则,它将被丢弃。

卫东

赞同来自:

如果您正在使用
Array.push


你可以做到以下


var a = ["1"]
a.push/... !true ? ["2"] : []/


结果-
["1"]


或者


var a = ["1"]
a.push/... true ? ["2"] : []/


结果是这样的
["1","2"]

要回复问题请先登录注册