美文网首页
Array filter()应用实例

Array filter()应用实例

作者: 浪客行1213 | 来源:发表于2019-06-14 10:38 被阅读0次

Array filter()

filter 直译 过滤器 显然起到的效果是过滤、筛选;
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意
  1. filter() 不会对空数组进行检测。
    2.filter() 不会改变原始数组.

语法

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

实例应用及参数分析

基本用法

//定义一个数组
var ages = [32, 33, 16, 40];
//定义一个函数 返回大于18的元素
  function checkAdult(age) {
      return age >= 18;
  }
//返回原数组大于18的元素组成新的数组
  var newAges = ages.filter(checkAdult);

参数分析

var ages = [32, 33, 16, 40];
var newAges= ages .filter((item,index,ages) => { 逻辑运算  return boolean; },thisVue);
             //item 要检测的数组的当前元素  好比 遍历中的一个元素;  必选参数
            //index 当前元素在原数组中的下标索引   可选参数
            //ages 调用filter的当前数组,用于作用域的问题,可能需要传入;  可选参数
            //return boolean类型的数组;
            //filter的参数2 thisVue ; 作用域this 严格模式下filter的回调函数中的this = thisVue传入的值,也是因作用域的问题,选择性传入;
            /*官方所说:如果为 `filter` 提供一个 `thisArg` 参数,则它会被作为 `callback` 被调用时的 `this` 值。
              否则,`callback` 的 `this` 值在非严格模式下将是全局对象,严格模式下为 `undefined`。
            `callback` 函数最终观察到的 `this` 值是根据[通常函数所看到的 "this"的规则](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this)确定的。
            */

var age = 18;
 var newAges2 = ages .filter((item,index,ages) => {
    return item>this; //这里的this就是filter传入的参数2 age;
  },age);
console.log(newAges2 );
//  打印结果 32/33/40

浪客行1213的简书


xhh

相关文章

网友评论

      本文标题:Array filter()应用实例

      本文链接:https://www.haomeiwen.com/subject/wcxufctx.html