1.map()方法
适用场景:
- 需要利用某种规则映射得到一个新数组
作用:
- 遍历每一个元素,并对每一个元素做相应的处理,返回一个新数组
注意事项:
- 回调函数执行次数 == 数组长度
-
数组中有几个元素,回调函数就会执行几次
-
回调函数中一定要return,返回的才会是当前遍历的元素值,否则新数组的每一个元素都是undefined
语法:
- ((元素,下标) => {return})
实例
需求:将数组中每个元素+1
let a = [1,2,3,4]; let b = a.map((value,index) => { return value + 1; }) console.log(b); //输出结果:[2,3,4,5]
2. filter()方法
适用场景:
- 用于筛选数组中满足条件的所有元素,并返回筛选后的新数组
注意事项:
- 回调函数的执行次数 == 数组长度
-
filter函数返回的新数组长度不等于原数组长度
-
回调函数一定要return一个布尔值,如果return的值为true,当前遍历的元素就会添加到新数组中,如果return的值为false,则不会添加到新数组中
语法:
- 数组.filter((item.index) => {})
实例
需求:找出数组中的所有偶数
let a = [1,2,3,4,5,6] let b = a.filter((value =>{ reutrn value % 2 ==0 }) console.log(b);//输出结果:2,4,6
3.forEach()方法
适用场景:
-
用于遍历数组,相当于for循环另一种写法
注意事项:
- 回调函数的执行次数等于数组长度
-
forEach函数没有返回值
-
回调函数不需要return,就算手动return,也不会结束循环
-
forEach必须提供一个参数
语法:
- 数组.forEach(function(value,index,arr){//算法})
实例
需求:对下列数组进行累加
let a = [1,2,3,4,5,100] // 利用for循环方法 let b = 0; for (let i = 0; i < a.length; i++) { b += a [i] } console.log(b);//输出结果:115 //利用forEach方法 let c = 0; a.forEach(function(value) { c += value }) console.log(c);//输出结果:115
4.some()方法
适用场景:
-
用于判断数组中是否存在满足条件的元素
注意事项:
-
回调函数执行次数 != 数组长度
-
some函数返回一个布尔类型值
-
回调函数返回布尔类型值用于结束遍历
语法:
- 数组.some((item,index) => {})
实例:
需求:判断数组中是否有负数
let a = [-1,1,2,3,4] let b = a.some((item,index) => { return item < 0 }); console.log(b);//返回结果:true
5.every()方法
适用场景:
-
用于判断数组中是否所有元素都满足条件
注意事项:
- every函数返回一个布尔类型值
语法:
- 数组.every((item) => {})
实例
需求:判断数组中是否所有元素都 > 0
let a = [-1,0,1,2,3] let b = a.every((item) => { return item > 0 ; }); console.log(b); //返回结果:false
6. findIndex()方法
适用场景:
- 适用于数组中元素为对象类型,比传统的for循环要高效
作用:
- 获取符合条件的第一个元素的位置(下标)
注意事项:
-
如果return的值为true,则遍历结束,findIndex方法返回值为当前的index值;如果return的值为false,则遍历继续,如果数组全部遍历完还是没有返回true,则findIndex方法返回值为-1.
语法:
- 数组名.findIndex((item,index) => {return true/false})
实例
需求:筛选出符合条件的第一个元素的位置
let a = [ {name:'一一',age:'11'}, {name:'二二',age:'22'}, {name:'三三',age:'33'}, {name:'四四',age:'44'}, {name:'五五',age:'55'}, ] let b = a.findIndex((item,index) => { return item.age < 30; }) console.log(b); //返回值:0
7.reduce()方法
适用场景:
-
数组求和/平均数/最大/最小值
作用:
-
遍历数组元素,为每个数组执行一次回调函数
注意事项:
-
最好给一个初始值,避免空数组报错
语法:
- 数组名.deruce((sum,value) =>{return sum + value})
实例
需求:
求出数组中所有元素的和
let a = [1,2,3,4,5] //sum:初始值,默认为数组第一个元素. //value:数组的每一个元素,默认为数组第二个元素 let b = a.reduce((sum,value) =>{ //等效于 sum = sum + value return sum + value; }) console.log(b); // 返回值:15 //简写 console.log(a.reduce((sum,value) => sum + value)); //15
求出数组中的最大值
let a = [1,2,3,4,5] let c = a.reduce((sum,value) =>{ return sum > value ? sum : value; }) console.log(c);//返回值:5