[b]Array.prototype.reduce()[/b]
[b]概述[/b]
reduce()方法是数组的一个实例方法(共有方法),可以被数组的实例对象调用。reduce() 方法接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。
[b]语法[/b]
[code]arr.reduce(callback[, initialValue]) {}[/code]
[b]参数[/b]
回调函数中可以传递四个参数。
[b]previousValue[/b]:上一次调用回调函数返回的值,或者是提供的初始值(initialValue)
[b]currentValue[/b]:数组中当前被处理的元素
[b]currentIndex[/b]:当前被处理元素在数组中的索引, 即currentValue的索引.如果有initialValue初始值, 从0开始.如果没有从1开始
[b]array[/b]:调用 reduce 的数组
[b]initialValue[/b]:可选参数, 作为第一次调用 callback 的第一个参数
[b]返回值[/b]
reduce()返回值是最后一次调用回调函数返回的结果
[b]描述[/b]
reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,接受四个参数:
[list=1]
[*]previousValu 上一次值[/*]
[*]currentValue 当前值[/*]
[*]currentIndex 当前值的索引[/*]
[*]array 数组[/*]
[/list]
[b]回调函数第一次执行时[/b],previousValue 和 currentValue可能是两个不同值其中的一个,如果reduce有initialValue参数,那么 previousValue 等于 initialValue ,并且currentValue 等于数组中的第一个值;如果reduce没有 initialValue 参数,那么previousValue 等于数组中的第一个值,currentValue等于数组中的第二个值。
[b]注意[/b]: 如果没有initialValue参数, reduce从index为1开始执行回调函数, 跳过第一个index。 如果有initialValue参数, reduce 将从index为 0 开始执行回调
如果数组是空的并且没有initialValue参数, 将会抛出TypeError错误. 如果数组只有一个元素并且没有初始值initialValue, 或者有initialValue但数组是空的, 这个唯一的值直接被返回而不会调用回调函数。
通常来说提供一个initialValue初始值更安全一点, 因为没有的话会出现如下输出结果。
//没有提供initialValue
function foo(){
return [1,2,3,4,5].reduce((x, y) => x + y); //15
};
console.log(foo.call(this));
function foo(){
return [].reduce((x, y) => x + y); //TypeError
};
console.log(foo.call(this));
//提供initialValue
function foo(){
return [].reduce((x, y) => x + y, 0); //0
};
console.log(foo.call(this));
[b]reduce()是如何工作的[/b]
[0, 1, 2, 3, 4].reduce((previousValue, currentValue, index, array) => previousValue + currentValue);
回调被执行四次,每次的参数和返回值如下表:
[img]http://files.jb51.net/file_images/article/201612/201612121445348.jpg[/img]
reduce 的返回值是回调函数最后一次被调用的返回值(10)。
如果把初始值作为第二个参数传入 reduce,结果如下,结果如下:
[0, 1, 2, 3, 4].reduce((previousValue, currentValue, index, array) => previousValue + currentValue, 10);
[img]http://files.jb51.net/file_images/article/201612/201612121445349.jpg[/img]
最后一次函数调用的返回值 (20) 作为reduce函数的结果被返回
[b]注意:[/b]添加了initialValue参数会多调用一次回调函数
[b]例题[/b]
[b]将数组所有项相加[/b]
let sum = [0, 1, 2, 3, 4].reduce((x, y) => x + y, 0);
// 10
[b]扁平化一个二维数组[/b]
let arr = [[1, 2], [3, 4], [5, 6]].reduce((x, y) => x.concat(y), []);
// [1, 2, 3, 4, 5, 6]
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持编程素材网!