0%

array.map(fn)

map() 方法

  • map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

  • 语法:array.map(function(currentValue,index,arr), thisValue)

  • callback 为数组中每个元素执行的函数,该函数可接受1-3个参数

    • currentvalue 参数表示数组的当前元素项,必须的参数

    • index 参数表示的当前元素下标,可选参数

    • arr 参数表示当前元素所属的数组,可选参数

  • thisValue 表示执行回调函数 callback() 时的 this 指向。可选参数。当不写时,则默认是指向 window 全局

手写 map

简单版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Array.prototype._map = function (fn) {
if (typeof fn !== 'function') return 'fn is not a function'
let temp = []
const arr = this
for(let val of arr) {
temp.push(fn(val))
}
return temp
}

const arr = [1, 2, 3, 4]

const res = arr._map(item => {
return '_' + item + '_'
})

console.log(res) // [ '_1_', '_2_', '_3_', '_4_' ]

完全版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Array.prototype.__map = function (fn, ctx) {
if (typeof fn !== 'function') return 'fn is not a function'
const arr = this
let temp = []
let l = arr.length
for (let i = 0; i < l; i++) {
temp.push(fn.call(ctx, arr[i], i, arr))
}
return temp
}

arr.__map(function (curVal, idx, arr) {
console.log(curVal, idx, arr)
})

/**
* 1 0 [ 1, 2, 3, 4 ]
2 1 [ 1, 2, 3, 4 ]
3 2 [ 1, 2, 3, 4 ]
4 3 [ 1, 2, 3, 4 ]
*/

reduce 版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Array.prototype.___map = function (fn, ctx) {
if (typeof fn !== 'function') return 'fn is not a function'
let temp = []
this.reduce((total, curVal, idx, arr) => {
temp.push(fn.call(ctx, curVal, idx, arr))
}, [])
return temp
}

arr.___map(function (curVal, idx, arr) {
console.log(curVal, idx, arr)
})

/**
* 1 0 [ 1, 2, 3, 4 ]
2 1 [ 1, 2, 3, 4 ]
3 2 [ 1, 2, 3, 4 ]
4 3 [ 1, 2, 3, 4 ]
*/
-------------本文结束感谢您的阅读-------------