假设我有一个数组定义
var array = [
"One",
"Two",
"Three",
]
...但我只想在另一个变量为真时添加“三”。
var array = [
"One",
"Two",
(addThree ? "Three" : undefined),
]
问题是,如果 addThree 为 false,则数组变为 ["One","Two",undefined] 而我只想将其变为 ["One","Two"]。
最佳答案
你可以拿Array#concat
和一个 conditional (ternary) operator ?:
用于检查 addThree
并获取值或空数组。
空数组不会改变返回数组的长度。
var addThree = false,
array = ["One", "Two"].concat(addThree ? "Three" : []);
console.log(array);
关于javascript - 添加条件数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51581822/