是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
这样看看:
for(var i in array){
if(array[i]=='seven'){
array.splice(i,1);
break;
}
}
在函数中:
function removeItem(array, item){
for(var i in array){
if(array[i]==item){
array.splice(i,1);
break;
}
}
}
removeItem(array, 'seven');
其他回答
你可以使用underscore.js。这真的让事情变得简单。
例如,用这个:
var result = _.without(['three','seven','eleven'], 'seven');
结果是[' 3 ',' 11 ']。
在你的情况下,你必须写的代码是:
ary = _.without(ary, 'seven')
它减少了你编写的代码。
在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf(item);//item: the value which you want to remove
//Method 1
ary.splice(index,1);
//Method 2
delete ary[index]; //in this method the deleted element will be undefined
var index = array.indexOf('item');
if(index!=-1){
array.splice(index, 1);
}
非破坏性拆卸:
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;
}
在所有唯一的值中,您可以:
a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5}
[...a] // [1, 2, 4, 5]