filter函数的使用方法

1.filter的相关简介

filter方法是js中常用的方法

一,filter函数通常用于对数组进行过滤。它创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。注意:filter()不会对空数组进行检测、不会改变原始数组   

二,语法;Array.filter(function(currentValue, index, arr))其中,函数 function 为必须,数组中的每个元素都会执,其中的currentValue是遍历的当前值,index是遍历值在原数组中的位置,arr是原数组。

2.filter的相关使用方法

 如下在函数中我们可以看出,for循环和filter都能完成对应的具体的要求,但是相比于for循环来说,filter的使用更加的简洁,且在遍历的过程中可以获取到原来的数组。比较的方便,且多掌握一种遍历数组的方法。就会有多一种的相关选择。

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];


//找出元素中比五大的数并输出
let result = []

const get_resultArr = () => {
  
 for(let i =0 ;i 5){
       result[result.length++] = nums[i]
     }
   }
  //其中的三个参数分别为 当前遍历的值 当前值的下标 所筛选的数组 
  result = nums.filter((currentValue, index, arr) => {
    console.log(currentValue, index, arr);
    return currentValue > 5
  })
}
get_resultArr()
console.log(result,nums);

利用filter打印的result和num是 [6, 7, 8, 9, 10]   [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

你可能感兴趣的:(JS,javascript,开发语言,ecmascript)