JavaScript Array Remove

大牛John Resig写的Array Remove方法

第一种:扩展JavaScript的内置对象Array

// 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);

第二种:

第二种方法的操作方式与上一种一样,但是不影响全局对象,相当于给JavaScript内置的Array添加了一个静态方法

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

原文地址:http://ejohn.org/blog/javascript-array-remove/

发表评论

电子邮件地址不会被公开。 必填项已用*标注