使用原型,重写了数组的push、pop、shift、unshift几个简单的方法。
我在这抛砖引玉,期待大神更多对象的其他的方法扩展
Array.prototype.push = function(){
//this: 1,2,3
//arguments: 4,5,6
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i];
}
return this.length;
}
Array.prototype.pop = function(num){
if (num) {
this.length = this.length-num
}else{
this.length = this.length-1;
}
return this.length;
}
Array.prototype.shift = function(){
for (var i = 1; i < this.length; i++) {
this[i-1] =this[i];
}
this.length = this.length -1;
return this.length;
}
Array.prototype.unshift = function(){
for (var i = this.length-arguments.length-1; i >= 0; i--) {
this[arguments.length+i] = this[i];
}
for (var j = 0; j < arguments.length; j++) {
this[j] =arguments[j];
}
return this.length;
}
var arr = new Array();
arr = [1,2,3];
arr.push(4,5,6);
alert(arr);
arr.pop();
alert(arr);
arr.shift();
alert(arr);//2,3,4,5
arr.unshift("a","b");
alert(arr);//a,b,2,3,4,5