簡體   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