是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
方法1
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1
if (index > -1) { //if found
ary.splice(index, 1);
}
方法2
一条衬垫
var ary = ['three', 'seven', 'eleven'];
filteredArr = ary.filter(function(v) { return v !== 'seven' })
// Or using ECMA6:
filteredArr = ary.filter(v => v !== 'seven')
其他回答
var remove = function(array, value) {
var index = null;
while ((index = array.indexOf(value)) !== -1)
array.splice(index, 1);
return array;
};
CoffeeScript + jQuery变体:
arrayRemoveItemByValue = (arr,value) ->
r=$.inArray(value, arr)
unless r==-1
arr.splice(r,1)
# return
arr
console.log arrayRemoveItemByValue(['2','1','3'],'3')
它只移除一个,而不是全部。
从数组中删除所有匹配的元素(而不仅仅是第一个,这似乎是这里最常见的答案):
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' });
你可以像这样使用indexOf方法:
var index = array.indexOf(item);
if (index !== -1) {
array.splice(index, 1);
}
注意:对于IE8及以下版本,您需要对其进行填充
Var数组= [1,2,3,4] Var项= 3 var index = array.indexOf(item); 数组中。拼接(指数(1); console.log(数组)