1. 程式人生 > 實用技巧 >js 實現一個Array.prototype.filter()

js 實現一個Array.prototype.filter()

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

    let resArr = []
    const me = this

    const ctx = context ? context : this // 判斷上下文

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

    me.forEach((item, index) => {
        const bool = fn.call(ctx, item, index, me) // 繫結上下文,並執行結果
        if (bool) { // 如果符合條件,就放進新的陣列
            resArr.push(item)
        }
    })

    return resArr
}

下面來驗證一下

const arr = [1,2,3]

const newArr = arr.my_filter(function(item, index, _arr) {
    console.log(this, item, index, _arr)
    return item >= 2
})

console.log(newArr)

再來驗證一下繫結上下文

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

const newArr = arr.my_filter(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_filter(1, arr1)

console.log(newArr)