高阶函数
什么是高阶函数
- 高阶函数
(Higher-order funciton)
- 可以把函数作为参数传递给另一个函数
- 可以把函数作为另一个函数的返回结果
- 函数作为参数
function forEach(arr, callback) {
for (let i = 0; i < arr.length; i++) {
callback(arr[i], i)
}
}
const arr = ['张三', '里斯', '卫庄']
forEach(arr, function(item, i) {
console.log(item, i)
})
function filter(arr, callback) {
const result = []
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
result.push(arr[i])
}
}
return result
}
const res = filter(arr, item => {
if (item === '卫庄') return item
})
console.log(res)
function once(fn) {
let done = false
return function() {
if (!done) {
done = true
return fn.apply(this, arguments)
}
}
}
const pay = once(function(menoy) {
console.log(menoy)
})
pay(5)
pay(5)
常用高阶函数
- forEach
- map
- filter
- every
- some
- find/findIndex
- reduce
- sort
- …
const map = (array, callback) => {
const result = []
for (let value of array) {
result.push(callback(value))
}
return result
}
const arr = [1, 3, 4, 5, 9]
const result = map(arr, v => v * v)
console.log(result)
const every = (array, callback) => {
let result = true
for (let value of array) {
result = callback(value)
if (!result) break
}
return result
}
const arr1 = [10, 31, 3, 21]
const result1 = every(arr1, v => v > 10)
const result2 = every(arr1, v => v > 1)
console.log(result1)
console.log(result2)
const some = (array, callback) => {
let result = false
for (let value of array) {
result = callback(value)
if (result) break
}
return result
}
const arr2 = [1, 3, 5]
const result3 = some(arr1, v => v % 2 === 0)
const result4 = some(arr2, v => v % 2 === 0)
const find = (array, callback) => {
let result
for (let value of array) {
if (callback(value)) {
result = value
}
}
return result
}
const arr = ['javascript', 'vue', 'react', 'typescript']
const res = find(arr, v => v === 'vue')
console.log(res)
const findIndex = (array, callback) => {
let index
for (let i in array) {
if (callback(array[i])) {
index = i
}
}
return index
}
const res = findIndex(arr, v => v === 'vue')
console.log(res)
const reduce = (array, callback, initVal) => {
let initValue = initVal || 0
for (let i = 0; i < array.length; i++) {
initValue = callback(initValue, array[i], i, this)
}
return initValue
}
const res = reduce([1,2,3,4], (prev, item) => prev + item)
console.log(res)
|