一、reduce实现
reduce的用法:
arr.reduce(function(pre,cur,index,arr){...return...}, initialValue);
arr是原数组,可以传入两个参数,第一个参数是有返回值的函数,该函数可以有四个传参(前一个具有累加器性质的元素,当前元素,索引,原数组),第二个是初始值,可以选择性设置。
实现:
// arr.reduce(function(pre,cur,index,arr){...}, initialValue);
Array.prototype.myReduce = function(fn,initialValue){
if(typeof fn !== "function"){
throw new TypeError("argument[0] is not a function")
}
let initialArr = this;
let arr = initialArr.concat();
let index;
if(arguments.length==2){
arr.unshift(initialValue);
index = 0;
}else{
index = 1;
}
let res;
if(arr.length===1){
res = arr[0];
}
while(arr.length>1){
res = fn.call(null,arr[0],arr[1],index,arr)
index++;
arr.splice(0,2,res);
}
return res;
}
// 验证
var arr= [1,3,2,5,2,34];
var res = arr.myReduce(function(pre,cur,index,arr){
console.log(index); // 索引从1开始
return pre+cur;
})
console.log(res); // 47
var res1 = arr.myReduce(function(pre,cur,index,arr){
console.log(index); // 索引从0开始
return pre+cur;
},3)
console.log(res1); // 50
二、map实现
map的用法:
arr.map(function(item,index,arr){...return...},context)
arr是原数组,可以传入两个参数,第一个参数是有返回值的函数,该函数可以有三个传参(当前元素,索引,原数组),第二个是上下文,可以选择性设置。
// arr.map(function(item,index,arr){...return...},context)
// 方法一:使用for循环实现
Array.prototype.myMap = function (fn, context){
if(typeof fn !== 'function'){
throw new TypeError("arguments[0] is not a function");
}
let arr = this;
let res = [];
for(let i = 0; i < arr.length; i++){
res.push(fn.call(context, arr[i], i, arr));
}
return res;
}
// 方法二:使用reduce函数实现
Array.prototype.newMap = function(fn,context){
if(typeof fn !== 'function'){
throw new TypeError("arguments[0] is not a function");
}
let arr = this;
let res = [];
arr.reduce((pre, cur, index, arr) => {
res.push(fn.call(context, cur, index, arr));
}, 0)
return res;
}
// 验证
let array = [1, 2, 3, 4, 5];
let myArr = array.myMap(function(item,index){
return item * index;
})
console.log(myArr);
let newArr = array.newMap(function(item,index){
return item * index;
})
console.log(newArr);