是否有从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]

其他回答

你可以用以下两种方法:

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

ES6路。

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);

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

CoffeeScript + jQuery变体:

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

它只移除一个,而不是全部。

这可以是一个全局函数或一个自定义对象的方法,如果你不允许添加到本机原型。它从数组中删除与任何参数匹配的所有项。

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

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

ary.remove('seven');

/*  returned value: (Array)
three,eleven
*/

使之成为全球性的

function removeA(arr) {
    var what, a = arguments, L = a.length, ax;
    while (L > 1 && arr.length) {
        what = a[--L];
        while ((ax= arr.indexOf(what)) !== -1) {
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary = ['three', 'seven', 'eleven'];
removeA(ary, 'seven');


/*  returned value: (Array)
three,eleven
*/

并照顾IE8及以下-

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(what, i) {
        i = i || 0;
        var L = this.length;
        while (i < L) {
            if(this[i] === what) return i;
            ++i;
        }
        return -1;
    };
}