繁体   English   中英

从数组中删除特定元素

[英]Remove specific elements from array

我得到了这个代码:

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值。

使用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;
    }
});

请参阅此线程以了解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;
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM