数组方法重构
1.调用方式
2.参数 是否改变原数组
3.功能
4.返回值
//mypop 删除最后一个元素并返回删除的元素
Array.prototype.myPop = function(){
if(this.length=''){
return undefined;
}else{
var temp = this[this.length - 1];
this.length--;
return temp;
}
}
var arr = [1,2,3,4,5];
var res = arr.myPop();
console.log(res);
console.log(arr);
//myPush 向数组末尾添加一个或多个元素并返回新长度
Array.prototype.myPush = function(){
for(var i = 0;i < arguments.length;i++){
this[this.length] = arguments[i];
}
return this.length;
}
var arr = [1,2,3,4,5];
var res = arr.myPush('hello','a');
console.log(res);
console.log(arr);
//myShift 删除数组第一个元素并返回值
Array.prototype.myShift = function(){
var res = this[0];
for(i = 0;i<this.length;i++){
this[i] = this[i+1];
}
this.length--;
return res;
}
var arr = [1,2,3,4,5];
var res = arr.myShift('hello','a');
console.log(res);
console.log(arr);
//myUnshift 向开头添加一个或多个元素并返回新长度
Array.prototype.myUnshift = function(){
var res = this.length + arguments.length;
for(var i = result;i>0;i--){
if(i>arguments.length){
this[i-1] = this[i-1-arguments.length];
}else{
this[i-1] = atguments[i-1];
}
}
return res;
}
var arr = [1,2,3];
var res = arr.myShift('hello','a');
console.log(res);
console.log(arr);
//myForEach 调用数组每个元素,将元素传递给回调函数
Array.prototype.myForEach = function(fun){
for(i=0;i<this.length;i++){
fun(this[i],i,this);
}
}
var arr = [1,2,3,4,5];
var res = arr.myForEach(function(item,index,arr){
console.log(item + '--' + index + '--' +arr);
})
// every
Array.prototype.myEvery = function(fun,obj){
for(i=0;i<this.length;i++){
if(!(obj?fun.bind(obj)(this[i]):fun(this[i]))){
return false;
}
}
return true;
}
var arr = [1,2,3,4,5];
var result = arr.myEvery(function(item,index,arr){
console.log(this);
return item>1;
},{name:'zhangsan'})
console.log(result);
// some
Array.prototype.mySome = function(fun,obj){
for(i=0;i<this.length;i++){
if((obj?fun.bind(obj)(this[i]):fun(this[i]))){
return true;
}
}
return false;
}
var arr = [1,2,3,4,5];
var result = arr.mySome(function(item,index,arr){
console.log(this);
return item>1;
},{name:'zhangsan'})
console.log(result);
// map
Array.prototype.myMap = function(fun,obj){
var result = [];
for(i=0;i<this.length;i++){
// obj?test():test2()
result.push(obj?fun.bind(obj)(this[i]):fun(this[i]));
}
return result;
}
var arr = [1,2,3,4,5];
var result = arr.myMap(function(item,index,arr){
console.log(this);
return item+1;
},{name:'zhangsan'})
console.log(result);
// filter
Array.prototype.myFilter = function(fun,obj){
var result = [];
for(i=0;i<this.length;i++){
if(obj?fun.bind(obj)(this[i]):fun(this[i])){
result.push(this[i]);
}
}
return result;
}
var arr = [1,2,3,4,5];
var result = arr.myFilter(function(item,index,arr){
console.log(this); //打印5次
return item>2;
},{name:'zhangsan'})
console.log(result);