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

标签 javascript arrays

如何从数组中删除特定值?比如:

array.remove(value);  // removes all elements with value

我必须使用 core JavaScript。不允许使用框架。

最佳答案

使用 indexOf 查找要删除的数组元素的 index ,然后使用 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) { // only splice array when item is found
  array.splice(index, 1); // 2nd parameter means remove one item only
}

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

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


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

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 中,这些函数可以通过类型参数保持类型安全:

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

关于javascript - 如何从数组中删除特定项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5767325/

相关文章:

javascript - jQuery 事件性能 : Bind a single event on parent or individual events on each child?

java - Arrays.asList 是否违反了 Liskov 替换原则?

javascript - 将字符串数组转换为 JAVASCRIPT 对象

javascript - 使用 Axios 取消之前的 API 请求

javascript - Webpack、IE8 和 ES6 模块

javascript - 如何根据内容对 JSON 中的字段进行计数

javascript - nsIXMLHttpRequest 仅执行到readyState 1

java - 是什么导致 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

javascript - 如何将具有相同键的两个对象(关联数组)合并为一个对象

java - 这些声明有什么区别?这与一个可变而另一个不可变有关吗?