JavaScript ES6 Array.filter()方法总结

本篇文章参考以下博文

一、定义

   filter() 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

   filter 的中文意思是“筛选”,顾名思义,会对数组中的元素挨个进行检查,检查通过的,才能组成新的数组。

二、语法

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
  • callback
    用来测试数组的每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数:
    • element
      数组中当前正在处理的元素。
    • index 可选
      正在处理的元素在数组中的索引。
    • array 可选
      调用了 filter 的数组本身。
  • thisArg 可选
    执行 callback 时,用于 this 的值。

三、实例

3.1 过滤数组中的假值

let array= [false, null, undefined, NaN, 0, ""]
array.filter(Boolean)  // []

3.2 数组中不同的部分

let arr1 = [1, 2, 3, 4], arr2 = [3, 4, 5];
let arr= [...arr1, ...arr2].filter(item => !arr1.includes(item) || !arr2.includes(item)) //[1, 2, 5]

3.3 数组去重

let arr = ['name','age','friends','height','weight','name','age']
let newArr = arr.filter((v, index)=> {
    return arr.indexOf(v) === index // 该元素第一次在数组中出现的位置是否等于当前索引值
})

四、转化为 ES5 之后的源码

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, // 这一步是保证 this.length 为正整数
        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 是为了保证 this.length 为正整数,具体解释戳 这里




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值