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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

在所有唯一的值中,您可以:

a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5} 
[...a] // [1, 2, 4, 5]

其他回答

请不要使用带有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' ]

另一个变化:

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循环。

方法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')

你可以像这样使用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(数组)

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

例如,用这个:

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

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

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

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

它减少了你编写的代码。