@1 数组reduce方法的使用:
const arr = [1,2,3,4,5]
reduce可以接受两个参数,先来看只有一个函数参数是如何执行的
const total = arr.reduce((res,item,index)=>{
第一次循环 res=1 item = 2 index = 1 返回的结果为3
第二次循环 res=3(上一次迭代返回的结果) item = 3 index = 2 返回的结果为6
第三次循环 res=6 item = 4 index = 3 返回的结果为10
第四次循环 res=10 item = 5 index = 4 返回的结果为15
return res+item
})
得到的结果为15 ;
reduce接受第二个参数:第一个参数为函数,第二个参数为累计的起始值;
const total = arr.reduce((res,item,index)=>{
第一次循环 res=0 item = 1 index = 0 返回的结果为1
第二次循环 res=1(上一次迭代返回的结果) item = 2 index = 1 返回的结果为3
第三次循环 res=3 item = 3 index = 2 返回的结果为6
...... 以此类推
return res+item
},0)
得到的结果依然为15
@2 再来看下数组求和的其他方法吧:
let total = 0
arr.forEach(item=>{
total+=item
})
console.log(total)
、、、、、、、、、、、、、、、、、、、、
arr.join('+') // '1+2+3+4+5'
eval('1+2+3+4+5') // 15
console.log(eval(arr.join(‘+’)))
@3 利用reduce求和;
封装函数:
function fn(...arguments){
return function (...ags){
return arguments.concat(ags).reduce(res,item=>res+item)
}
}
代码简写:const fn =(...arguments)=>(...ags)=>arguments.concat(ags).reduce(...)
const res = fn(1,2,3)(4) // 结果为 10