如果满足条件,如何将元素添加到数组

问题描述 投票:-1回答:8

有一个箭头函数创建一个数组,如:

const myFunction = () => ["a", "b", "c"];

我想为它添加一个参数,如果参数为true,则必须添加另一个元素。

像这儿:

const myFunction = (arg) => ["a", "b", "c", arg ? "d" : null];

这个解决方案的问题是,如果arg !== true仍然添加一个null元素,但我想在这种情况下不添加任何内容。

javascript arrays ternary-operator arrow-functions
8个回答
2
投票

您可以使用数组传播。根据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"]

1
投票

你可以使用concat

const myFunction = (arg) => ["a", "b", "c"].concat(arg ? ["d"] : []);

console.log(myFunction(true));
console.log(myFunction(false));

1
投票

你可以使用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));

0
投票

你可以让功能更长一点,

  • 创建一个临时数组,
  • 如果需要,将元素附加到临时数组,
  • 完成后返回临时数组

const myFunction = (arg) => {
  var tempArray = ["a", "b", "c"];
  
  if (arg) {
    tempArray.push("d");
  }
  
  return tempArray;
};

console.log(myFunction(true) + "");
console.log(myFunction(false) + "");

0
投票
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返回它,那么使用其他解决方案。


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));

0
投票

Ori有the right answer。将其用于所有现代浏览器。如果由于某种原因你仍然停留在较旧的浏览器上 -

["a", "b", "c"].concat(arg ? 'd' : [])

0
投票

如果将数组存储在变量中,可以像下面这样:

const arr = ["a", "b", "c"];
const myFunction = arg => arg === true ? [...arr, "d"] : arr;

console.log(myFunction(true));
console.log(myFunction());
© www.soinside.com 2019 - 2024. All rights reserved.