且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从数组中删除特定项目?

更新时间:2023-01-17 18:02:30

使用 indexOf,然后使用 splice.

Find the index of the array element you want to remove using indexOf, and then remove that index with splice.

splice() 方法通过删除现有元素和/或添加新元素.

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 

splice 的第二个参数是要移除的元素数量.请注意,splice 修改了数组并返回一个包含已删除元素的新数组.

The second parameter of splice is the number of elements to remove. Note that splice modifies the array in place and returns a new array containing the elements that have been removed.

为了完整起见,这里是函数.第一个函数只删除一个匹配项(即从 [2,5,9,1,5,8,5] 中删除 5 的第一个匹配项),而第二个函数删除所有出现的:

For the reason of completeness, here are functions. The first function removes only a single occurrence (i.e. removing the first match of 5 from [2,5,9,1,5,8,5]), while the second function removes all occurrences:

function removeItemOnce(arr, value) {
  var index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}

function removeItemAll(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}
// Usage
console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
console.log(removeItemAll([2,5,9,1,5,8,5], 5))

在 TypeScript 中,这些函数可以通过类型参数保持类型安全:

In TypeScript, these functions can stay type-safe with a type parameter:

function removeItem<T>(arr: Array<T>, value: T): Array<T> { 
  const index = arr.indexOf(value);
  if (index > -1) {
    arr.splice(index, 1);
  }
  return arr;
}