定义和用法
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
js实现
// fn是callback函数,thisValue是参数
Array.prototype.mymap = function ( fn , thisValue ){
let temp = []
// this就是调用map()方法的数组
let arr = this
// 循环数组项
for(let i = 0; i < arr.length; i++){
// 对每一项使用传入的fn()方法
let result = fn.call(thisValue ,arr[i] , i, arr)
// 将每次fn()方法返回的值存储到新数组中,如果fn()没有返回值,result为undefined
temp.push(result)
}
// 返回一个新数组
return temp
}
使用:
let aa = [1,4,2,33]
let bb = aa.mymap(function (item,key,arr){
return item*2
})
console.log(bb) // 输出 [ 2, 8, 4, 66 ]