JS数组方法

xiaoxiao2021-02-28  22

1.reduce

带初始值调用:

 

let arr = [1,2,3,4,5] let result = arr.reduce((pre,next)=>{ console.log('上一次结果为:'+pre) console.log('下一个值为:'+next) return pre+next },13) console.log('最终结果为:'+result)

输出结果:

 

 

上一次结果为:13 下一个值为:1 上一次结果为:14 下一个值为:2 上一次结果为:16 下一个值为:3 上一次结果为:19 下一个值为:4 上一次结果为:23 下一个值为:5 最终结果为:28

不带初始值调用:

 

 

let arr = [1,2,3,4,5] let result = arr.reduce((pre,next)=>{ console.log('上一次结果为:'+pre) console.log('下一个值为:'+next) return pre+next }) console.log('最终结果为:'+result)

输出结果:

 

 

上一次结果为:1 下一个值为:2 上一次结果为:3 下一个值为:3 上一次结果为:6 下一个值为:4 上一次结果为:10 下一个值为:5 最终结果为:15

带初始值时,第一次的pre为初始值,next为arr[0],进行arr.length次迭代

 

不带初始值时,第一次的pre为arr[0],next为arr[1],进行arr.length-1次迭代  

转载请注明原文地址: https://www.6miu.com/read-2626824.html

最新回复(0)