从数组中删除特定元素

时间:2014-04-30 14:45:18

标签: javascript arrays

我收到了这段代码:

Object.defineProperty(Array.prototype, "remove", {
    enumerable: false,
    value: function (item) {
        var removeCounter = 0;

        for (var index = 0; index < this.length; index++) {
            if (this[index] === item) {
                this.splice(index, 1);
                removeCounter++;
                index--;
            }
        }

        return removeCounter;
    }
});

我尝试使用以下代码行从数组特定元素中删除:

var itemsRemoved = finalArray.remove(getBack);

但是,如果我执行console.log(),则返回0个元素,而我的变量getBack等于0或其他数字,并且数组中的getBack值存在。

2 个答案:

答案 0 :(得分:0)

使用item.indexOf(this[index])代替this[index] === item

为什么呢? item是一个数组而不是单个值:

Object.defineProperty(Array.prototype, "remove", {
    enumerable: false,
    value: function (item) {
        var removeCounter = 0;

        for (var index = 0; index < this.length; index++) {
            console.log(this[index], item);
            if (item.indexOf(this[index]) > -1) {
                this.splice(index, 1);
                removeCounter++;
                index--;
            }
        }

        return removeCounter;
    }
});

答案 1 :(得分:0)

请参阅this thread有关js中对象比较的信息

快速实现目标:

Object.defineProperty(Array.prototype, "remove", {
    enumerable: false,
    value: function (item) {
        var removeCounter = 0;

        for (var index = 0; index < this.length; index++) {
            if (JSON.stringify(this[index]) === JSON.stringify(item)) {
                this.splice(index, 1);
                removeCounter++;
                index--;
            }
        }

        return removeCounter;
    }
});