如何从数组中删除特定值?比如:
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/