如何从数组中删除特定项目? [英] 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);
我必须使用 core JavaScript.不允许使用框架.
I have to use core JavaScript. Frameworks are not allowed.
推荐答案
使用 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))
这篇关于如何从数组中删除特定项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!