是否有从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');

其他回答

真的,我不明白为什么不能用

arr = arr.filter(value => value !== 'seven');

或者你可能想使用普通的JS

arr = arr.filter(function(value) { return value !== '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

我尝试使用上面jbaron中的函数方法,但发现我需要保持原始数组完整以供以后使用,并创建一个像这样的新数组:

var newArray = referenceArray;

显然是通过引用而不是值创建的,因为当我从newArray中删除一个元素时,referenceArray也删除了它。所以我决定每次创建一个新数组,就像这样:

function newArrRemoveItem(array, item, newArray){
    for(var i = 0; i < array.length; i++) {
        if(array[i]!=item){
            newArray.push(array[i]);
        }
    }
}

然后我在另一个函数中这样使用它:

var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);

现在,vesselArr保持完整,而每次我执行上述代码时,othervessel数组都包含了除最新的vesselID元素之外的所有元素。

你要的是滤镜

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

非破坏性拆卸:

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;
}