数组的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 +