数组的reduce()用法
用法:对数组的每一项进行累加,最后返回一个总数,
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
- reduce()接受一个回调函数和initialValue这个参数 ,数组调用reduce()时,数组的每一项都会执行传入的回调函数,将结果累加,最终返回一个总值,initialValue累计值的初始值,可选参数
- 回调函数有四个参数,分别是accumulator累加值,currentValue当前正在遍历的数组元素,index,当前正在遍历的数组元素对应的索引,array调用的reduce的数组。其中index,和array为可选参数
- 如果initialValue有值的话,accumulator累加值取initialValue的值,currentValue取调用数组的第一项,index = 0;如果没值的话,accumulator累加值就取调用数组的第一项,currentValue取调用数组的第一项,index = 1.
举个列子:
let arr = [ 1, 2, 3 ]
//输出6
console.log(arr.reduce((accumulator,currentValue) => { return accumulator + currentValue}));
//输出16
console.log(arr.reduce((accumulator,currentValue) =>{ return accumulator + currentValue},10))

这篇博客探讨了JavaScript数组的reduce()方法,重点强调了在处理空数组和包含对象元素时的注意事项。如果不提供initialValue初始值,空数组调用reduce()会抛出错误。同时,当数组元素为对象时,必须提供初始值以避免意外的累加行为,否则可能导致错误。通过示例,博主提醒开发者要细心避免此类bug。
5883

被折叠的 条评论
为什么被折叠?



