首页 > Web开发 > 详细

js 实现一个Array.prototype.filter()

时间:2020-08-05 23:32:17      阅读:117      评论:0      收藏:0      [点我收藏+]
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)

技术分享图片

js 实现一个Array.prototype.filter()

原文:https://www.cnblogs.com/bejamin/p/13443291.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!