有一个箭头函数创建一个数组,如:
const myFunction = () => ["a", "b", "c"];
我想为它添加一个参数,如果参数为true,则必须添加另一个元素。
像这儿:
const myFunction = (arg) => ["a", "b", "c", arg ? "d" : null];
这个解决方案的问题是,如果arg !== true
仍然添加一个null元素,但我想在这种情况下不添加任何内容。
您可以使用数组传播。根据arg
的值,一个空数组或包含d
的数组将被传播到结果数组中:
const myFunction = (arg) => ["a", "b", "c", ...arg ? ['d'] : []];
console.log(JSON.stringify(myFunction(true))); // ["a","b","c","d"]
console.log(JSON.stringify(myFunction())); // ["a","b","c"]
你可以使用concat
:
const myFunction = (arg) => ["a", "b", "c"].concat(arg ? ["d"] : []);
console.log(myFunction(true));
console.log(myFunction(false));
你可以使用Array push()。
const myFunction = (arg) => {
const arr = ["a", "b", "c"];
if (arg) arr.push("d");
return arr;
};
console.log(myFunction(true));
console.log(myFunction(false));
你可以让功能更长一点,
const myFunction = (arg) => {
var tempArray = ["a", "b", "c"];
if (arg) {
tempArray.push("d");
}
return tempArray;
};
console.log(myFunction(true) + "");
console.log(myFunction(false) + "");
const myFunction = (arg) => {
ret = ['a', 'b', 'c']
return arg === true ? ret.concat('d') : ret;
}
在其他解决方案中,你有arg ?
而不是arg === true ?
。如果你想让myFunction
仅使用'd'
为arg = true
返回数组,那么你应该使用我的解决方案。如果你想让它返回'd'
,例如,arg = 17
,但不是为arg = 0
返回它,那么使用其他解决方案。
你也可以这样做:
const myMethod = (arg) => {
var tempArray = ["item 1", "item 2", "item 3"];
!arg || tempArray.push("item 4");
return tempArray;
};
console.log(myMethod(false));
console.log(myMethod(true));
Ori有the right answer。将其用于所有现代浏览器。如果由于某种原因你仍然停留在较旧的浏览器上 -
["a", "b", "c"].concat(arg ? 'd' : [])
如果将数组存储在变量中,可以像下面这样:
const arr = ["a", "b", "c"];
const myFunction = arg => arg === true ? [...arr, "d"] : arr;
console.log(myFunction(true));
console.log(myFunction());