您的位置:首页 > Web前端 > JavaScript

JavaScript数组添加remove()方法

2010-12-14 17:04 627 查看
第一种:

Javascript代码

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

};  

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


这个函数扩展了JavaScript的内置对象Array,这样,我们以后的所有声明的数组都会自动的拥有remove能力

用法:

Javascript代码

var array = ["one", "two", "three", "four", "five", "six"];   

array.remove(0);//删除第一个元素   

array.remove(-1);//删除倒数第一个元素   

array.remove(0,2);//删除数组中下标为0-2的元素(3个)  

var array = ["one", "two", "three", "four", "five", "six"];
array.remove(0);//删除第一个元素
array.remove(-1);//删除倒数第一个元素
array.remove(0,2);//删除数组中下标为0-2的元素(3个)


第二种:

Javascript代码

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

};  

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


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

用法:

Javascript代码

var array = ["one", "two", "three", "four", "five", "six"];   

Array.remove(array, 0, 2);//删除0, 1, 2三个元素  

http://zdeming.javaeye.com/blog/664684
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息