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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

你可以使用without或pull from Lodash:

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

其他回答

请不要使用带有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' ]
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);

if (index > -1) {
   arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]

你可以使用underscore.js。这真的让事情变得简单。

例如,用这个:

var result = _.without(['three','seven','eleven'], 'seven');

结果是[' 3 ',' 11 ']。

在你的情况下,你必须写的代码是:

ary = _.without(ary, 'seven')

它减少了你编写的代码。

一行代码就可以了,

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

// Remove item 'seven' from array
var filteredArray = arr.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredArray = arr.filter(e => e !== 'seven')

这就使用了JS中的filter函数。它在IE9及更高版本中得到支持。

它的功能(来自文档链接)

Filter()为数组中的每个元素调用一次所提供的回调函数,并构造一个包含所有回调返回强制为true的值的新数组。回调只对数组中已赋值的索引调用;对于已删除或从未赋值的索引,不调用该方法。未通过回调测试的数组元素将被跳过,并且不包含在新数组中。

基本上,这和所有其他for (var key in ary){…}解决方案,除了从IE6开始支持for in构造。

基本上,filter是一个方便的方法,与for in构造(AFAIK)相比,它看起来更好(并且是可链的)。

另一个变化:

if (!Array.prototype.removeArr) {
    Array.prototype.removeArr = function(arr) {
        if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
        var that = this;
        if(arr.length){
            var i=0;
            while(i<that.length){
                if(arr.indexOf(that[i])>-1){
                    that.splice(i,1);
                }else i++;
            }
        }
        return that;
    }
}

它又是循环中的indexOf(),但前提是要删除的数组相对于要清理的数组较小;每次移除都会缩短while循环。