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()
不能扩展以满足我的需求,您对我上面的其他解决方案有何看法?