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




语法

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"));



参考资料

《菜鸟教程》


版权声明:本文为qq_41996454原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。