将元素添加到数组的末尾

Add elements to the end of an array

我正在尝试解决来自 jshero.net 的挑战。

挑战是:

Write a function add that adds an element to the end of an array. However, the element should only be added if it is not already in the array. add([1, 2], 3) should return [1, 2, 3] and add([1, 2], 2) should return [1, 2].

问题是 Array:indexOf()。有谁知道怎么解决吗?

您可以尝试使用Array.prototype.includes检查数组中是否存在数字

function add(arr, number) {
  if (arr.includes(number)) return arr;
  else return [...arr, number];

}

console.log(add([1,2], 3));
console.log(add([1,2], 2));

您也可以使用 Array.prototype.indexOf:

function add(arr, number) {
  if (arr.indexOf(number) > -1) return arr;
  else return [...arr, number];

}

console.log(add([1,2], 3));
console.log(add([1,2], 2));