reduce
reduce
是JavaScript 1.8中才引入的,中文意思为“减少”、“约简”。不过,从功能来看,我个人是无法与“减少”这种含义联系起来的,反而更接近于“迭代”、“递归(recursion)”,擦,因为单词这么接近,不会是ECMA-262 5th制定者笔误写错了吧~~
![](https://i-blog.csdnimg.cn/blog_migrate/1ef81c12626eb08f01a8ccaa51a4908e.gif)
此方法相比上面的方法都复杂,用法如下:
array.reduce(callback[, initialValue])
callback
函数接受4个参数:之前值、当前值、索引值以及数组本身。initialValue
参数可选,表示初始值。若指定,则当作最初使用的previous
值;如果缺省,则使用数组的第一个元素作为previous
初始值,同时current
往后排一位,相比有initialValue
值少一次迭代。
var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
return previous + current;
});
console.log(sum); // 10
说明:
- 因为
initialValue
不存在,因此一开始的previous
值等于数组的第一个元素。 - 从而
current
值在第一次调用的时候就是2
. - 最后两个参数为索引值
index
以及数组本身array
.
以下为循环执行过程:
// 初始设置 previous = initialValue = 1, current = 2 // 第一次迭代 previous = (1 + 2) = 3, current = 3 // 第二次迭代 previous = (3 + 3) = 6, current = 4 // 第三次迭代 previous = (6 + 4) = 10, current = undefined (退出)
有了reduce
,我们可以轻松实现二维数组的扁平化:
var matrix = [ [1, 2], [3, 4], [5, 6] ]; // 二维数组扁平化 var flatten = matrix.reduce(function (previous, current) { return previous.concat(current); }); console.log(flatten); // [1, 2, 3, 4, 5, 6]