可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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"]
But if I set cond
to false
, I get the following result: ["foo", false]
How could I define an array with a conditional element?
回答1:
You can spread an array inside of an array, in order to keep items array clean, when the condition is 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 []
.
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.
In other answer I explained the same idea, but for objects. You can check it too here.
回答2:
I'd do this
[
true && 'one',
false && 'two',
1 === 1 && 'three',
1 + 1 === 9 && 'four'
].filter(Boolean) // ['one', 'three']
Note that this will also remove falsy values, such as empty strings.
回答3:
You can try with a simple if :
if(cond) {
myArr.push("bar");
}
回答4:
If you really want to keep it as a one liner, you could use:
const cond = true;
const myArr = ["foo"].concat(cond ? ["bar"] : []);
回答5:
You don't have so many options other than using 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);
回答6:
There's a few different ways, but the way you're doing it won't really work for Javascript.
The easiest solution would be to just have an if statement.
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).
var arr = ["a", cond && "bar"];
arr.filter( e => e)
Basically it will just filter out all the non true values.
回答7:
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.
回答8:
if you are using es6, I would suggest
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.
回答9:
if you use Array.push
You can do follow
var a = ["1"]
a.push(... !true ? ["2"] : [])
Result is ["1"]
or
var a = ["1"]
a.push(... true ? ["2"] : [])
Result is
["1","2"]