filter相关知识点小结

filter

基本语法

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

  1. 参数
  • callback 回调函数 true 是返回元素 false 过滤掉次元素
    • element 当前正在处理的函数
    • index 当前正在处理的函数的索引值
    • array 调用 filter 函数的数组
  • thisArg
    • 执行 callback 时,用于 this 的值。
    • 只有下面 this 的值是 undecided,其余 this 的值是 Window
      "use strict";
    let num = [0, 1, 2, 3, 4];
    const res = num.filter(function (value) {
      console.log(this);//打印的值为undecided
      return value > 2;
    });
  1. filter 不会改变原数组,它返回过滤后的新数组,需要一个新的数组来接受结果

  2. 实现原理剖析

  function myfilter(arr, callback) {
      let newArr = [];
      for (const value of arr) {
        if (callback(value) === true) newArr.push(value);
      }
      return newArr;
    }
    console.log(
      myfilter(num, function (item) {
        return item > 2;
      })
    );

原理解释

  • 需要传入一个数组和一个回调函数作为参数
  • 创建一个新的数组来接受结果
  • 通过回调函数的判断结果 将符合的数据压入新的数组
  • 最后返回新的数组

实例

let num = [0, 1, 2, 3, 4];
   const res = num.filter((value) => value > 2);
   console.log(res); // {3,4}

补充

filter 被添加到 ECMA-262 标准第 5 版中,因此在某些实现环境中不被支持。可以把下面的代码插入到脚本的开头来解决此问题,该代码允许在那些没有原生支持 filter 的实现环境中使用它。该算法是 ECMA-262 第 5 版中指定的算法,假定 fn.call 等价于 Function.prototype.call 的初始值,且 Array.prototype.push 拥有它的初始值。

if (!Array.prototype.filter){
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
        throw new TypeError();

    var len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;
    if (thisArg === undefined){
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func(t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }
    else{
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func.call(thisArg, t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }

    res.length = c; // shrink down array to proper size
    return res;
  };
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ベ远行ミ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值