如何在JavaScript中从数组中删除特定项?
如何在JavaScript中从数组中删除特定项?
如何从数组中移除特定的值?就像这样:
array.remove(value);
限制条件:我必须使用核心 JavaScript。不允许使用框架。
2016年10月编辑
- 保持简单、直观和明确(奥卡姆剃刀原理)
- 使用不可变的方式(原始数组保持不变)
- 使用标准的JavaScript函数,如果你的浏览器不支持它们-使用polyfill
在这个代码示例中,我使用array.filter(...)
函数从数组中移除不需要的项。这个函数不会改变原始数组并创建一个新数组。如果你的浏览器不支持这个函数(例如Internet Explorer 9之前的版本或Firefox 1.5之前的版本),请考虑使用使用core-js
进行polyfill。
移除项(ECMA-262版5代码也称为旧版JavaScript)
var value = 3 var arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(function(item) { return item !== value }) console.log(arr) // [ 1, 2, 4, 5 ]
删除项目(ECMAScript 6 代码)
let value = 3 let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => item !== value) console.log(arr) // [ 1, 2, 4, 5 ]
重要提示,Internet Explorer在版本45之前,Chrome在版本45之前,Firefox在版本22之前,Safari在版本10之前均不支持ECMAScript 6的() => {}
箭头函数语法。要在旧浏览器中使用ECMAScript 6语法,可以使用BabelJS。
删除多个项目(ECMAScript 7 代码)
使用这种方法的另一个好处是可以删除多个项目
let forDeletion = [2, 3, 5] let arr = [1, 2, 3, 4, 5, 3] arr = arr.filter(item => !forDeletion.includes(item)) // !!! Read below about array.includes(...) support !!! console.log(arr) // [ 1, 4 ]
重要提示,Internet Explorer在任何版本中均不支持array.includes(...)
函数,Chrome在版本47之前,Firefox在版本43之前,Safari在版本9之前,Edge在版本14之前也不支持,但您可以使用使用core-js进行兼容性支持。
移除多个元素(将来也许)
如果"this-binding syntax"建议被接受,你就可以这样做:
// array-lib.js export function remove(...forDeletion) { return this.filter(item => !forDeletion.includes(item)) } // main.js import { remove } from './array-lib.js' let arr = [1, 2, 3, 4, 5, 3] // :: This-Binding Syntax Proposal // using "remove" function as "virtual method" // without extending Array.prototype arr = arr::remove(2, 3, 5) console.log(arr) // [ 1, 4 ]
参考资料
使用indexOf
找到要移除的数组元素的索引,然后使用splice
移除该索引。
splice() 方法通过删除现有元素和/或添加新元素来更改数组的内容。
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(arr: Array , value: T): Array { const index = arr.indexOf(value); if (index > -1) { arr.splice(index, 1); } return arr; }