繁体   English   中英

仅在满足条件的情况下如何将元素添加到数组

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM