js 手写一个Array.prototype.map()方法

Array.prototype.my_map = function(fn, context) {

    let resArr = []
    const me = this

    const ctx = context ? context : me // 定义上下文

    if (typeof fn !== 'function') {
        throw new Error(`${fn} is not a function`)
    }

    me.forEach((item, index) => {
        resArr.push(fn.call(ctx, item, index, me)) // 将回调结果放入数组中
    })

    return resArr // 返回map后的数组
}

下面来验证一下

const arr = [1,2,3]

const newArr = arr.my_map(function(item, index, _arr) {
    console.log(this, item, index, _arr)
    return item * 2
}, arr1)

console.log(newArr)

可以看到还是比较成功的,再来验证一下上下文有没有绑定成功

const arr = [1,2,3]
const arr1 = [4,5,6]

const newArr = arr.my_map(function(item, index, _arr) {
    console.log(this, item, index, _arr)
    return item * 2
}, arr1)

console.log(newArr)

再看一下错误处理

const arr = [1,2,3]
const arr1 = [4,5,6]

const newArr = arr.my_map(123, arr1)

console.log(newArr)

ok!大功告成了

posted @ 2020-08-05 22:20  毛小星  阅读(1482)  评论(0编辑  收藏  举报