依照 ecma262 草案,实现的map的规范如下: 首先手写map函数:
map方法接收两个参数,第一个为函数,第二个一般为this,我们在使用map函数的时候,一般只用添加函数即可。
let arr=[1,2,3,4,5];
Array.prototype.mapArray=function(fn,thisArgs){
let length=this.length;
console.log(this)
console.log(thisArgs)
let res=[];
if(!Array.isArray(this)) throw new TypeError('this is not an array');
if(typeof fn!=='function'){
throw "error";
}
if(length==0){
return res;
}
for(let i=0;i<length;i++){
res.push(fn.call(thisArgs,this[i],i,this));
}
return res;
}
var p= arr.mapArray((item,index,arr)=>{
return item+1;
})
console.log(p)
大家可以仔细这个map方法的实现!
依照
ecma262
草案,实现的
reduce
的规范如下
:
下面我们实现手写reduce
var arr=[1,2,3,4,5];
Array.prototype.reduceArr=function(fn,initvalue){
if(typeof fn!='function'){
throw new Error('current params in not correct');
}
let arr=this;
let initIndex;
let acc;
initIndex=arguments.length==1?1:0;
acc=arguments.length===1?arr[0]:initvalue;
for(let i=initIndex;i<arr.length;i++){
acc= fn(acc,arr[i],i,arr);
}
return acc;
}
console.log(arr.reduceArr((pre,cur)=>{
return pre+cur;
},20))
最后输出了35。
下面实现push,pop 方法:
参照 ecma262 草案的规定,关于 push 和 pop 的规范如下图所示:
push方法:
let arr=[1,2,3,4,5];
Array.prototype.pusharr=function(...value){
let arr=this;
let arrlength=this.length;
let length=value.length;
for(let i=0;i<length;i++){
arr[arrlength+i]=value[i];
}
arr.length=arrlength+length;
return arr.length;
}
arr.pusharr(1,2,4);
console.log(arr)
最后实现一下filter方法:
Array.prototype.filterArr=function(callback,thisArg){
let arr=this;
if(!Array.isArray(arr)){
throw "error";
}
if(typeof callback!='function'){
throw 'error';
}
let length=arr.length;
let res=[];
for(let i=0;i<length;i++){
if(callback.call(thisArg,arr[i],i,arr)){
res.push(arr[i]);
}
}
return res;
}
var arr=[1,2,3,4,5];
var p=arr.filterArr(item=>{
return item>3
})
console.log(p)