数组之map方法详解 桃扇骨 2024-04-08 13:29 27阅读 0赞 原理: map作用是映射调用此方法的数组,不会改变原始数组,返回原始数组每一项的操作,组成一个新数组,长度和原始数组一致 方法: Array.map((item,index,arr)=>{ //item => 数组的每一项 //index => 数组每一项的索引 //arr => 原数组 }) 实例: let arr = [1,2,3] let newArr = arr.map((item,index,arr)=>{ return item+1 }) //newArr = [2,3,4] 封装map function myMap(fn){ //this是调用此方法的数组 let newArr = [] for(let i = 0;i<this.length;i++){ let result = fn(this[i],i,this) newArr.push(result) } return newArr } Array.prototype.myMap = myMap 实例: let arr = [1,2,3] let newArr = arr.maMap((item,index,arr)=>{ return item+1 }) //newArr = [2,3,4]
还没有评论,来说两句吧...