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!大功告成了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM