-
Notifications
You must be signed in to change notification settings - Fork 0
/
_reduce.js
36 lines (32 loc) · 843 Bytes
/
_reduce.js
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
Array.prototype._reduce = function _reduce(executor, initial) {
if (!this || this.constructor !== Array) {
throw new TypeError('_reduce的调用方式不正确!');
}
let accumulator,
arr = this,
len = arr.length,
idx = 0;
if (initial == undefined) {
for (; idx < len; idx++) {
if (idx in arr) {
accumulator = arr[idx++];
break;
}
if (len === 0) {
break;
}
if (idx === len) {
break;
}
}
} else {
accumulator = initial;
}
for (; idx < len; idx++) {
let item = arr[idx];
if (idx in arr) {
accumulator = executor.call(null, accumulator, item, idx, arr);
}
}
return accumulator;
}