介绍
- 数组的七种迭代方法分别是:map,filter,forEach,every,some,findIndex, reduce
1. map()方法
- 作用: 映射,将数组的每一项元素进行处理,并返回一个新的数组
- 应用示例
let arr = [1, 2, 3, 4]
let dealArr = arr.map((item, index) => item + 1)
console.log(dealArr)
2. filter()方法
let filterArr = [
{name: 'lisi', age: 22},
{name: 'zhangsan', age: 23},
{name: 'wangwu', age: 24},
{name: 'wanger', age: 25},
]
let dealFilterArr = filterArr.filter((item, index) => item.age > 23)
console.log(dealFilterArr)
3. forEach()方法
let arr = [1, 2, 3, 4]
arr.forEach((item, index) => console.log(item))
4. every() 方法
- 作用:判断数组中的元素是否所有元素符合条件,只有全部符合条件才会返回true,否则返回false
- 应用示例
let arr2 = [
{name: 'lisi', age: 22},
{name: 'zhangsan', age: 23},
{name: 'wangwu', age: 24},
{name: 'wanger', age: 25},
]
let isEvery = arr2.every((item, index) => item.age > 18)
let isEvery = arr2.every((item, index) => item.age > 24)
5. some()方法
- 作用:判断数组中元素是否存在符合条件的元素,只要存在符合条件的元素就返回true,否则返回false
- 应用示例
let arr2 = [
{name: 'lisi', age: 22},
{name: 'zhangsan', age: 23},
{name: 'wangwu', age: 24},
{name: 'wanger', age: 25},
]
let isSome = arr2.some((item, index) => item.age == 23)
let isSome = arr2.some((item, index) => item.age == 26)
6. findIndex()方法
- 作用:查找第一个符合条件的元素的下标,找不到返回-1
- 应用示例
let arr2 = [
{name: 'lisi', age: 22},
{name: 'zhangsan', age: 23},
{name: 'wangwu', age: 23},
{name: 'wanger', age: 25},
]
let index = arr2.findIndex((item, index) => item.age == 23)
let index = arr2.findIndex((item, index) => item.age == 2)
7. reduce()方法
- 作用: 遍历数组元素,每一个元素都要执行一次回调函数,接收两个参数:
- 第一个参数:(pre, cur, index, arr) => {}
- 第二个参数: pre初始值(第二个参数默认取数组第一个参数)
- 应用示例
let arr = [1, 2, 3, 4]
let addNum = arr.reduce((pre, cur, index, arr)=> pre + cur, 0)
let arr = [1, 2, 3, 4]
let addNum = arr.reduce((pre, cur, index, arr)=> pre + cur, 0)
let averageNum = addNum/arr.length
let arr3 = [12, 35, 64, 46, 23, 1, 67]
let isreduce = arr3.reduce((pre, cur, index, arr) => pre > cur ? pre : cur)
let arr3 = [12, 35, 64, 46, 23, 1, 67]
let isreduce = arr3.reduce((pre, cur, index, arr) => pre < cur ? pre : cur)
const nearNum = (arr, num) => arr.reduce((pre, cur, index, arr) => (Math.abs(cur - num) < Math.abs(pre - num) ? cur : pre))
let maxNum = nearNum([12, 35, 64, 46, 23, 1, 67], 33)