是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
你可以用以下两种方法:
const arr = ['1', '2', '3', '4'] // we wanna delete number "3"
第一种方式: arr.indexOf (3) ! = = 1 & & arr.splice (arr.indexOf (3), 1) 第二种方式(ES6)特别无突变: const newArr = arr。过滤(e => e !== '3')
其他回答
从数组中删除所有匹配的元素(而不仅仅是第一个,这似乎是这里最常见的答案):
while ($.inArray(item, array) > -1) {
array.splice( $.inArray(item, array), 1 );
}
我使用jQuery来完成这些繁重的工作,但是如果您想要本地化,您就可以理解了。
var remove = function(array, value) {
var index = null;
while ((index = array.indexOf(value)) !== -1)
array.splice(index, 1);
return array;
};
非破坏性拆卸:
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;
}
方法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')
请不要使用带有delete的变体-它会在数组中留下一个洞,因为它不会在删除的项之后重新索引元素。
> Array.prototype.remove=function(v){
... delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]