是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
最简单的解决方案是:
array—用于删除某些元素的数组valueForRemove; valueForRemove—用于删除的元素;
array.filter(arrayItem => !array.includes(valueForRemove));
更简单:
array.filter(arrayItem => arrayItem !== valueForRemove);
不漂亮,但有用:
array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))
不漂亮,但有用:
while(array.indexOf(valueForRemove) !== -1) {
array.splice(array.indexOf(valueForRemove), 1)
}
附注:filter()方法创建一个包含所有通过所提供函数实现的测试的元素的新数组。参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
其他回答
从数组中删除所有匹配的元素(而不仅仅是第一个,这似乎是这里最常见的答案):
while ($.inArray(item, array) > -1) {
array.splice( $.inArray(item, array), 1 );
}
我使用jQuery来完成这些繁重的工作,但是如果您想要本地化,您就可以理解了。
真的,我不明白为什么不能用
arr = arr.filter(value => value !== 'seven');
或者你可能想使用普通的JS
arr = arr.filter(function(value) { return value !== 'seven' });
非破坏性拆卸:
function removeArrayValue(array, value)
{
var thisArray = array.slice(0); // copy the array so method is non-destructive
var idx = thisArray.indexOf(value); // initialise idx
while(idx != -1)
{
thisArray.splice(idx, 1); // chop out element at idx
idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
}
return thisArray;
}
你要的是滤镜
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
这将允许你做以下事情:
var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']
这一点在其他地方也有注意到:https://stackoverflow.com/a/20827100/293492
鉴于没有一个漂亮的ES6函数,这里有一个简单且可重用的ES6函数。
const removeArrayItem = (arr, itemToRemove) => {
return arr.filter(item => item !== itemToRemove)
}
用法:
const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')