ES5 Array reduce方法的实现和使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
if (typeof Array.prototype.reduce != "function") {
Array.prototype.reduce = function (callback, initialValue ) {
var previous = initialValue,
k = 0,
length = this.length;
if (typeof initialValue === "undefined") {
previous = this[0];
k = 1;
}

if (typeof callback === "function") {
for (k; k < length; k++) {
this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this));
}
}
return previous;
};
}

var sum = [1, 2, 3, 4].reduce(function (previous, current, index, array) {
return previous + current;
});

document.write(sum+'</br>'); //10
var matrix = [
[1, 2],
[3, 4],
[5, 6]
];

// 二维数组扁平化
var flatten = matrix.reduce(function (previous, current) {
return previous.concat(current);
});

document.write(flatten); // [1, 2, 3, 4, 5, 6]