是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
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')
它只移除一个,而不是全部。
其他回答
你可以像这样使用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(数组)
非破坏性拆卸:
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;
}
这样看看:
delete this.arrayName[this.arrayName.indexOf(value)];
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
如果你有唯一的值,顺序不重要,使用Set,它有delete():
var mySet = new Set(['three', 'seven', 'eleven']);
mySet.delete('seven'); // Returns true, successfully removed
[...mySet]; // Returns ['three', 'eleven']
这样看看:
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');