是否有从JavaScript数组中删除项的方法?

给定一个数组:

var ary = ['three', 'seven', 'eleven'];

我想做的事情是:

removeItem('seven', ary);

我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。


当前回答

下面是一个使用jQuery的inArray函数的版本:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}

其他回答

在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示

 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

你可以使用Lodash _来实现这一点。删除功能。

Var array = [' 3 ', ' 7 ', ' 11 ']; Var even = _。删除(数组,函数(e) { 返回e !== 'seven'; }); console.log(均等的); <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script> .js

这样看看:

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');

下面是一个使用jQuery的inArray函数的版本:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}

你可以使用without或pull from Lodash:

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]