javascript - remove array element on condition

后端 未结 7 766
北荒
北荒 2020-11-29 05:39

I was wondering how I\'d go about implementing a method in javascript that removes all elements of an array that clear a certain condition. (Preferably without using jQuery)

相关标签:
7条回答
  • 2020-11-29 06:26

    You could add your own method to Array that does something similar, if filter does not work for you.

    Array.prototype.removeIf = function(callback) {
        var i = 0;
        while (i < this.length) {
            if (callback(this[i], i)) {
                this.splice(i, 1);
            }
            else {
                ++i;
            }
        }
    };
    

    To me, that's one of the coolest features of JavaScript. Ian pointed out a more efficient way to do the same thing. Considering that it's JavaScript, every bit helps:

    Array.prototype.removeIf = function(callback) {
        var i = this.length;
        while (i--) {
            if (callback(this[i], i)) {
                this.splice(i, 1);
            }
        }
    };
    

    This avoids the need to even worry about the updating length or catching the next item, as you work your way left rather than right.

    0 讨论(0)
提交回复
热议问题