JS之reduce

本文介绍了JavaScript中reduce方法的工作原理,重点解析了reduce回调函数的四个参数:previousValue、currentValue、index和array。文章通过说明有无初始值的情况,帮助读者理解reduce如何迭代数组并累积结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以前没接触到reduce
忽然遇见了这么个题:

martix = [[1,2],[3,4][5,6]]; var fl = martix.___(function(a,b)____); console.log(fl)//输出[1,2,3,4,5,6]

看看reduce

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
});

“MDNreduce”
reduce的callback含四个参数 previousValue, currentValue, index, array
reduce的作用
If initialValue is provided in the call to reduce, then previousValue will be equal to initialValue and currentValue will be equal to the first value in the array. If no initialValue was provided, then previousValue will be equal to the first value in the array and currentValue will be equal to the second.
有初始值,将初始值作为previousValue, 数组第0个值作为currentValue,以此类推
无初始值,将第0个值作为previousValue,数组第1个值作为currentValue,以此类推
现在懂了

martix = [[1,2],[3,4][5,6]]; var fl = martix.reduce(function(a,b){ return a.concat(b);}); console.log(fl)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值