Javascript 如何定义带有条件元素的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44908159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to define an array with conditional elements?
提问by Manu Schiller
how can i define conditional array elements? i want to do something like this:
我如何定义条件数组元素?我想做这样的事情:
const cond = true;
const myArr = ["foo", cond && "bar"];
this works as expected: ["foo", "bar"]
这按预期工作: ["foo", "bar"]
But if I set condto false, I get the following result: ["foo", false]
但是如果我设置cond为false,我会得到以下结果:["foo", false]
How could I define an array with a conditional element?
我如何定义一个带有条件元素的数组?
回答by Jordan Enev
You can spread an array inside of an array, in order to keep items array clean, when the condition is false.
当条件为 时,您可以在数组内展开数组,以保持 items 数组的清洁false。
Here's how you can do it:
您可以这样做:
// Will result in ['foo', 'bar']
const items = [
'foo',
... true ? ['bar'] : [],
... false ? ['falsy'] : [],
]
console.log(items)
Explanations:
说明:
As you can see the ternary operator always returns an array.
如您所见,三元运算符始终返回一个数组。
If the condition is true, then it returns ['bar'], otherwise an empty array [].
如果条件为true,则返回['bar'],否则返回空数组[]。
After that we spread out ...the resulted array (from the ternary operation) and the array's items are pushed to the parent array.
之后我们展开...结果数组(来自三元运算)并将数组的项推送到父数组。
If there aren't any array items (when the ternary check is false), then nothing will be pushed, which is our goal.
如果没有任何数组项(当三元检查为 时false),则不会推送任何内容,这是我们的目标。
In other answer I explained the same idea, but for objects. You can check it too here.
在其他答案中,我解释了相同的想法,但针对对象。你也可以在这里查看。
回答by Michael Bergquist Suarez
回答by Sylvain Attoumani
You can try with a simple if :
您可以尝试一个简单的 if :
if(cond) {
myArr.push("bar");
}
回答by James Thorpe
If you reallywant to keep it as a one liner, you could use:
如果您真的想将其保留为单衬,则可以使用:
const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);
回答by Alberto Trindade Tavares
You don't have so many options other than using push:
除了使用之外,您没有太多选择push:
const cond = true;
const myArr = ["foo"];
if (cond) myArr.push("bar");
Another idea is potentially adding null's and filtering them out:
另一个想法是可能添加空值并将其过滤掉:
const cond = true;
const myArr = ["foo", cond ? "bar" : null];
myArr = myArr.filter((item) => item !== null);
回答by Adam LeBlanc
There's a few different ways, but the way you're doing it won't really work for Javascript.
有几种不同的方法,但你这样做的方式并不真正适用于 Javascript。
The easiest solution would be to just have an if statement.
最简单的解决方案是只有一个 if 语句。
if (myCond) arr.push(element);
There's also filter, but I don't think that's what you want here at all, since you seem to be going for "Add this one thing, if this one condition is true" rather than checking everything against some condition. Although, if you want to get really freaky, you can do this (would not recommend, but it's cool that you can).
还有filter,但我认为这根本不是你想要的,因为你似乎想要“添加这件事,如果这一个条件为真”,而不是根据某个条件检查所有内容。虽然,如果你想变得非常怪异,你可以这样做(不推荐,但你可以这样做很酷)。
var arr = ["a", cond && "bar"];
arr.filter( e => e)
Basically it will just filter out all the non true values.
基本上它只会过滤掉所有非真实值。
回答by Jankapunkt
Alternative approach: Pre-Filter populate instead of post filtering:
替代方法:预过滤填充而不是后过滤:
const populate = function(...values) {
return values.filter(function(el) {
return el !== false
});
};
console.log(populate("foo", true && "bar", false && "baz"))
Returns
退货
(2) ["foo", "bar"]
I know that does not solve the shorthand notation (since it won't work no matter what you try) but it comes close to that.
我知道这并不能解决速记符号(因为无论您尝试什么都行不通),但它接近于此。
回答by Naxxa Consulting
if you are using es6, I would suggest
如果您使用的是 es6,我建议
let array = [
"bike",
"car",
name === "van" ? "van" : null,
"bus",
"truck",
].filter(Boolean);
let array = [
"bike",
"car",
name === "van" ? "van" : null,
"bus",
"truck",
].filter(Boolean);
This array will only contain value "van" if name equals "van", otherwise it will be discarded.
如果名称等于“van”,该数组将只包含值“van”,否则将被丢弃。
回答by Westman
const cond = false;
const myArr = ["foo", cond ? "bar" : null].filter(Boolean);
console.log(myArr)
Will result in ["foo"]
将导致 ["foo"]
回答by toffee
if you use Array.push
如果你使用 Array.push
You can do follow
你可以关注
var a = ["1"]
a.push(... !true ? ["2"] : [])
Result is ["1"]
结果是 ["1"]
or
或者
var a = ["1"]
a.push(... true ? ["2"] : [])
Result is
["1","2"]
结果是
["1","2"]

