Array API - filter()

210 阅读1分钟
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
​
//fiter函数 接收一个参数:作为其回调函数
const result = words.filter(word => word.length > 6);
​
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

语法

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

参数说明

  • callback() 回调函数,

    • 作用

      • 校验数组元素是否符合条件
    • 参数

      • element : 当前执行操作的数组元素
      • index:当前元素索引
      • array:原数组
    • 返回值 boolean

      • true 保留改元素到新数组
      • false 不保留
  • thisArg 执行回调函数时 this的值

返回值说明

  • 新数组

    • 空数组 --- 未有符合筛选条件的元素
    • 非空

特点

不改变原数组 仅返回过滤后数组
  • 注意:Vue2.x版本中 使用filter,无法响应式的将更新后数据渲染到页面中

应用 (完善ing)

  • 案例一:筛选数组元素中 值大于10的元素

        let array = [1, 2, 6, 10, 11, 12, 13, 15]
        let newArray = array.filter((eachItem) => {
          // 设置条件 
          return eachItem > 10
        })
        // 预期值:[11, 12, 13, 15]
        console.log("返回的新数组:",newArray);
    

    \