原生JS实现 fliter() 方法

定义和用法

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意: filter() 不会对空数组进行检测。

注意: filter() 不会改变原始数组。

语法

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

参数说明

参数 描述
function(currentValue, index,arr) 必须。函数,数组中的每个元素都会执行这个函数
函数参数:
参数 描述
currentValue 必须。当前元素的值
index 可选。当前元素的索引值
arr 可选。当前元素属于的数组对象
thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值为 "undefined"

具体实现 

// 实现filter
Array.prototype.filter = function(fn, value){
    if (typeof fn !== "function") {
        return false;
    }
    var arr = this;
    var temp = [];
    for (var i = 0; i < arr.length; i++) {
        var result = fn.call(value, arr[i], i, arr);
        if (result) temp.push(arr[i]);
    }
    return temp;
}

测试

var arr = ["a", "bb", "ccc", 100, 2222, 3111];
console.log(arr.filter(function(item){
    return typeof item === "string"
}));
console.log(arr.filter(function(item){
    return typeof item === "number"
}));

发布了167 篇原创文章 · 获赞 197 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/qq_17497931/article/details/104644147
今日推荐