今天就来实现一个简单的map方法
首先我们来看一下map方法的使用以及具体的参数
var arr = ["a","b","c","d","e"]; arr.map(function(currentValue,index,arr){ console.log("当前元素"+currentValue) console.log("当前索引"+index) console.log("数组对象"+arr) })
map的参数:
currentValue 必须。当前元素的值
index 可选。当期元素的索引值
arr 可选。当期元素属于的数组对象
我们先来屡屡思路,直接Array.map()就可以调用到map方法,那他应该是在原型链上的,然后接收一个匿名函数做参数,通过循环调用传入的匿名函数
下面我们来写一下试试
Array.prototype.newMap = function(fn) {
var newArr = [];
for(var i = 0; i<this.length; i++){
newArr.push(fn(this[i],i,this))
}
return newArr;
}
来,调用一下试一下子
arr.newMap((currentValue,index,arr)=>{ console.log("newMap当前元素"+currentValue) console.log("newMap当前索引"+index) console.log("newMap数组对象"+arr) })
Array.prototype.newMap = function(fn) {
var newArr = [];
for(var i = 0; i<this.length; i++){
newArr.push(fn(this[i],i,this))
}
return newArr;
}
var arr = [3, 4, 5];
var newArr = arr.newMap(function(item, index, arr) {
console.log(item, index, arr);
});
console.log(newArr);
//3 0 [3, 4, 5]
//4 1 [3, 4, 5]
//10 5 [3, 4, 5]
//[undefined, undefined, undefined]