您的位置:首页 > 其它

es5 reduce()

2016-05-07 15:43 239 查看
reduce
reduce
是JavaScript
1.8中才引入的,中文意思为“减少”、“约简”。不过,从功能来看,我个人是无法与“减少”这种含义联系起来的,反而更接近于“迭代”、“递归(recursion)”,擦,因为单词这么接近,不会是ECMA-262 5th制定者笔误写错了吧~~


此方法相比上面的方法都复杂,用法如下:

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]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: