1、数组pop方法重构
Array.prototype.myPop = function() {
var temp = this[this.length-1];
this.length--;
return temp;
}
2、数组push方法重构
Array.prototype.myPush = function(){
var len = this.length;
for(var key in arguments){
this[(len+(+key))] = arguments[key];
}
//可选方法,都能实现push效果
// for(var i=0; i<arguments.length; i++){
// this[this.length] = arguments[i]
// }
return this.length;
}
3、数组shift方法重构
Array.prototype.myShift = function(){
var res = this[0];
for(var i=0; i<this.length-1; i++){
this[i] = this[i+1]
}
this.length--;
return res;
}
4、数组unshift方法重构
Array.prototype.myUnshift = function(){
for(var i=this.length-1; i>=0; i--){
this[i+arguments.length] = this[i]
}
for(var j=arguments.length-1; j>=0; j--){
this[j] = arguments[j];
}
return this.length;
}
5、数组forEach方法重构
Array.prototype.myForEach = function(each) {
for(var i=0; i<this.length; i++){
each(this[i],i,this);
//each亦是一个函数
}
}
重构方法的使用与原方法一致