JS之filter()方法的使用

一、作用

filter用于对数组进行过滤。
它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

注意:filter()不会对空数组进行检测、不会改变原始数组

二、语法
Array.filter(function(currentValue, indedx, arr), thisValue)

其中,函数 function 为必须,数组中的每个元素都会执行这个函数。且如果返回值为 true,则该元素被保留;
函数的第一个参数 currentValue 也为必须,代表当前元素的值。

三、实例

返回数组nums中所有大于10的元素。

let nums = [7, 8, 9, 10, 11, 12, 13, 14, 15, 16];

let res = nums.filter((num) => {
  return num > 10;
});

console.log(res);  // [11,12, 13, 14, 15,16]

原文:https://www.jianshu.com/p/494226d9dd2c

原文地址:https://www.cnblogs.com/jessie-xian/p/11576379.html