什么是高阶函数?
高阶函数只是将函数作为参数或返回值的函数,可以使代码更简洁、高效。JS内置的数组高阶函数能够满足大部分数组操作,从此和for、while 说再见
1. map 创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。(映射)
const arr = [{ num: 1 }, { num: 2 }]
const newArr = arr.map( item => item.num * 2 )
// expected output: Array [2, 4]
2. filter方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。(过滤)
const arr = ["", null, undefined, 1]
const newArr = arr.filter(Boolean)
// expected output: Array [1]
3. reduce方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。(累加)
const arr = [{ num: 1 }, { num: 2 }]
// 累加对象
const newArr = arr.reduce((target, item) => {
target['num' + item.num] = item.num
return newObj
}, {})
// expected output: Object {num1: 1, num2: 2}
// 累加数组
const newArr = arr.reduce((target, item) => {
return target.concat(item.num)
}, [])
// expected output: Array [1, 2]
4. forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数(遍历)。
- 在ESlint中,出现返回值会报错
const obj = {foo: 1, bar: 2}
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
})
// expected output: foo 1 bar 2
5. every() 方法用于检测数组所有元素是否都符合指定条件(检测),some函数同理但相反
every() 方法使用指定函数检测数组中的所有元素:
- 如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
- 如果所有元素都满足条件,则返回 true。
const arr = [1, 30, 39, null, 10, 13]
const hasBig = arr.every(item => {
console.count()
return Number.isInteger(item)
})
// count: 4
// expected output: Boolean false
6. Array.from()
方法从一个类似数组或可迭代对象中创建一个新的,浅拷贝的数组实例。
console.log(Array.from({ length: 100 }, (_, key) => key));
// expected output: Array [0, 1, ..., 99]