[英]How to add an element to an array only if a condition is fulfilled
有一个箭头函数创建一个数组,如:
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
仅对arg = true
返回带有'd'
数组,那么您应该使用我的解决方案。 如果您希望它返回例如arg = 17
'd'
,但不希望它返回arg = 0
'd'
,请使用其他解决方案。
您也可以这样做:
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有正确的答案 。 将其用于所有现代浏览器。 如果由于某种原因您仍然停留在旧版浏览器上-
["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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.