<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 数组的reduce / reduceRight迭代方法
// reduce可以再迭代数组每一项的同时,实现结果的累积!在callback函数中
// + result: 存储的是上一轮处理的结果「也可能是数组第一项的值」
// + item: 当前选代这一项
// + index: 迭代这一项的索引
// 函数返回的值作为本轮处理的结果!!整个循环迭代结束后,把最后一轮的返回值,作为reduce执行的总结果!!
// reduce中传递的第二个参数,是为了给result赋值初始值的!
let arr = [10, 20, 30, 40]
let res = arr.reduce((result, item, index) => {
//第一轮:result数组第一项的值10 数组从第二项开始迭代:item=20 index=1 返回30
//第二轮:result是第一轮返回的结果30 item=30 index=2 返回60
// 第三轮:result是第二轮返回的结果60 item=40 index=3返回100
return result + item
})
// let res = arr.reduce((result, item, index) => {
// 第一轮:result是100 数组从第一项开始迭代:item=10 index=0 返回110
// 第二轮:result是110 item=20 index=1 返回130
// ...
// return result + item
// },100)
// console.log(res)
const a = x => x + 10
const b = x => x - 10
const c = x => x * 10
const d = x => x / 10
// 需求给定一个值100,依次执行上面的四个函数返回结果要怎么实现
const compose = function compose (...funcs) {
//funcs -> [a,b,c,d]
funcs.forEach(item => {
if (typeof item !== "function") {
throw new TypeError('传递进来的值必须为函数')
}
})
return function handle (x) {
//x=>100
let len = funcs.length
if (len === 0) return x
if (len === 1) return funcs[0](x)
return funcs.reduce((result, func, index) => {
//第-轮:result=x(100)func=a index=0 返回 a(100)=>110
//第二轮:result=110 func=b index=1 返回 b(110)=>100
// ...
return func(result)
}, x)
}
}
console.log(compose(a, b, c, d)(100));
</script>
</body>
</html>
数组的reduce 的使用和扁平化处理
于 2024-03-19 16:43:50 首次发布
本文介绍了JavaScript中的reduce方法,用于对数组进行累积计算,以及如何使用函数组合(compose)将多个函数顺序应用到一个值上。作者展示了如何使用reduce和一个自定义的compose函数实现给定值的连续函数应用。
摘要由CSDN通过智能技术生成