自己动手实现一个Array.prototype.filter?

本文深入解析JavaScript中Array.prototype.filter()方法的工作原理,包括其语法、参数及使用场景,并通过动手实现一个简单的myFilter()方法,帮助读者更好地理解和掌握这一核心数组操作技巧。




语法

array.filter(function(currentValue,index,arr), thisValue)
  • function(currentValue, index,arr)

必须。函数,数组中的每个元素都会执行这个函数

参数描述
currentValue必须。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
  • thisValue

可选。对象作为该执行回调时使用,传递给函数,用作 “this” 的值。
如果省略了 thisValue ,“this” 的值为 “undefined”

简单示例

let arr = ["x", "y", "z", 1, 2, 3];

console.log(arr.filter(item => typeof item === "string"));

动手实现

思路很简单。

  • 新建一个数组
  • 遍历原数组
    • 符合true就加入新数组
    • 不符合就跳过
  • 返回这个新建的数组
Array.prototype.myFilter = function (func, thisValue) {
    if (typeof func !== "function") {
        throw new TypeError('${func} is not a function')
    }
    
    let arr = thisValue || this;
    
    let result = [];

    for (let i = 0; i < arr.length; i++) {
        let tmp = func.call(thisValue, arr[i], i, arr);
        if (tmp)
            result.push(arr[i]);

    }
    return result;
}


let arr = ["x", "y", "z", 1, 2, 3];

console.log(arr.myFilter(item => typeof item === "string"));



参考资料

《菜鸟教程》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值