简体   繁体   English

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

[英]Remove element from array (splice)

Basic question on .splice() method, and how best to remove an element from an array. 关于.splice()方法的基本问题,以及如何最好地从数组中删除元素。

I want to remove an item from an array with .splice() but when I do, I want to have the original array minus the removed element returned. 我想用.splice()从数组中删除一个项目,但是当我这样做时,我想让原始数组减去已删除的元素。 .splice() returns the removed element instead. .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]

What's the best, and most eloquent way to do this? 什么是最好,最有说服力的方法呢?

Using the spread operator, you can do: 使用spread运算符,您可以:

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

Or if you want to use ES5, it can look something like: 或者如果你想使用ES5,它可能看起来像:

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

.splice mutates the array in place and returns the removed elements. .splice 在适当的位置改变数组并返回删除的元素。 So unless you actually need a function that returns the array itself, just access arr : 因此,除非您确实需要一个返回数组本身的函数,否则只需访问arr

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

You can create a wrapper function that performs the splice and returns the array: 您可以创建一个执行拼接并返回数组的包装函数:

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`

If you want to create a new array , without mutating the original array, you could use .filter : 如果要创建新数组 ,而不改变原始数组,可以使用.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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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