Резига, создатель 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