如何从数组中删除特定项目? [英] How can I remove a specific item from an array?
问题描述
我有一个数字数组,我正在使用 .push()
方法向其中添加元素.
I have an array of numbers and I'm using the .push()
method to add elements to it.
是否有一种简单的方法可以从数组中删除特定元素?
Is there a simple way to remove a specific element from an array?
我正在寻找类似的东西:
I'm looking for the equivalent of something like:
array.remove(number);
我必须使用核心 JavaScript.不允许使用框架.
I have to use core JavaScript. Frameworks are not allowed.
推荐答案
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;
}
这篇关于如何从数组中删除特定项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!