从数组中删除元素(拼接)

Pau*_*000 2 javascript arrays element splice

关于.splice()方法的基本问题,以及如何最好地从数组中删除元素.

我想从数组中删除一个项目,.splice()但是当我这样做时,我希望原始数组减去已删除的元素..splice()返回已删除的元素.

var arr = [1, 2, 3, 4, 5, 6, 7]
var newArr = arr.splice(3, 1)

console.log(newArr) // [4]

// whereas I want [1, 2, 3, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)

什么是最好,最有说服力的方法呢?

Tim*_*rts 6

使用spread运算符,您可以:

var arr = [1,2,3,4,5,6],
    indexToRemove = 3,
    newArr = [
      ...arr.slice(0,indexToRemove),
      ...arr.slice(indexToRemove+1)
    ]
Run Code Online (Sandbox Code Playgroud)

或者如果你想使用ES5,它可能看起来像:

var arr = [1,2,3,4,5,6],
    indexToRemove = 3,
    newArr = [].concat(arr.slice(0,indexToRemove)).concat(arr.slice(indexToRemove+1))
Run Code Online (Sandbox Code Playgroud)


Fel*_*ing 5

.splice 就地改变数组并返回删除的元素。因此,除非您实际上需要一个返回数组本身的函数,否则只需访问arr

var arr = [1, 2, 3, 4, 5, 6, 7]
arr.splice(3, 1)
console.log(arr) //  [1, 2, 3, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)

您可以创建一个执行拼接并返回数组的包装函数:

function remove(arr, index) {
  arr.splice(index, 1)
  return arr;
}

var newArr = remove(arr, 3);
// Note: `newArr` is not a new array, it has the same value as `arr`
Run Code Online (Sandbox Code Playgroud)

如果你想创建一个新数组,而不改变原始数组,你可以使用.filter

var newArr = arr.filter(function(element, index) {
  return index !== 3;
}); // [1, 2, 3, 5, 6, 7]
arr; // [1, 2, 3, 4, 5, 6, 7]
Run Code Online (Sandbox Code Playgroud)