昨天使用map方法的时候,突然感觉一直在直接用,也没有试试是怎么实现的,本来想直接搜一篇文章盘一下子,结果没搜到合适的,好吧,那就自己来写一下子吧今天就来实现一个简单的map方法首先我们来看一下map方法的使用以及具体的参数
var arr = ["a","b","c","d","e"];

arr.map(function(currentValue,index,arr){

console.log("当前元素"+currentValue)
console.log("当前索引"+index)

console.log("数组对象"+arr)

})
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
newArr.push(fn(this[i],i,this))

}

return newArr;

}
Array.prototype.newMap = function(fn) {

var newArr = [];

for(var i = 0; 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)

})

arr.newMap((currentValue,index,arr)=>{

console.log("newMap当前元素"+currentValue)

console.log("newMap当前索引"+index)

console.log("newMap数组对象"+arr)

})运行结果:可以看到我们的运行结果是完全一样的,到这里简单的map方法就实现了,可能有一些细节没注意到,没关系,只是给大家一个思路而已以上就是如何用JS模拟实现数组的map方法的详细内容,关于JS模拟实现数组的map方法的资料请关注其它相关文章!