約翰Resig的刪除索引的數組,jQuery的作者創建a very handy 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()
沒有擴展到適合我的需要,有什麼你覺得我上面的其他解決方案?
http://codereview.stackexchange.com/吧? – techfoobar
不要修改你不屬於自己的對象 - 即使J. Resig這樣做 – tmaximini
@techfoobar謝謝,不知道那個網站。 – Johan