1

jQuery 的创建者 John Resig 创建了一个非常方便的 Array.remove方法,我总是在我的项目中使用它:

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

它工作得很好。但我想知道它是否可扩展,以便它可以将索引数组作为第一个参数?

否则,我可能会制作另一种使用它的方法:

if (!Array.prototype.removeIndexes) {

    Array.prototype.removeIndexes = function (indexes) {

        var arr = this;

        if (!jQuery)
            throw new ReferenceError('jQuery not loaded');

        $.each(indexes, function (k, v) {

            var index = $.inArray(v, indexes);

            if (index !== -1)
                arr.remove(index);

        });
    };
}

如果Array.remove()不能扩展以满足我的需求,您对我上面的其他解决方案有何看法?

4

3 回答 3

2

我认为这就是您正在寻找的(它也适用于负索引):

if (!Array.prototype.removeIndexes) {

    Array.prototype.removeIndexes = function (indexes) {

        var arr = this;

        if (!jQuery) throw new ReferenceError('jQuery not loaded');

        var offset = 0;

        for (var i = 0; i < indexes.length - 1; i++) {
            if (indexes[i] < 0)
                indexes[i] = arr.length + indexes[i];
            if (indexes[i] < 0 || indexes[i] >= arr.length)
                throw new Error('Index out of range');
        }

        indexes = indexes.sort();

        for (var i = 0; i < indexes.length - 1; i++) {
            if (indexes[i + 1] == indexes[i])
                throw new Error('Duplicated indexes');
        }


        $.each(indexes, function (k, index) {
            arr.splice(index - offset, 1);
            offset++;
        });
        return arr;
    };
}

var a = ['a', 'b', 'c', 'd', 'e', 'f'];
var ind = [3, 2, 4];

a.removeIndexes(ind);

console.log(a.join(', '));
// returns : a, b, f 

见小提琴

于 2013-06-25T08:37:05.100 回答
1

这个版本应该可以工作。它修改了原始数组。如果您希望在不修改原始数组的情况下返回一个新数组,请使用注释掉的初始化程序并在函数末尾result添加。return result

Array.prototype.removeIndexes = function(indices) { 
  // make sure to remove the largest index first
  indices = indices.sort(function(l, r) { return r - l; });

  // copy the original so it is not changed
  // var result = Array.prototype.slice.call(this);

  // modify the original array
  var result = this;

  $.each(indices, function(k, ix) {
    result.splice(ix, 1);
  });
}

> [0, 1, 2, 3, 4, 5, 6, 7, 8].removeIndexes([4, 5, 1]);
> [0, 2, 3, 6, 7, 8]
于 2013-06-25T08:24:44.827 回答
0

怎么样

Array.prototype.remove = function (indexes) {
    if(indexes.prototype.constructor.name == "Array") {
        // your code to support indexes
    } else {
        // the regular code to remove single or multiple indexes
    }

};
于 2013-06-25T08:19:26.077 回答