ECMA5 Array 新增API reduce

时间:2023-03-09 01:19:58
ECMA5 Array 新增API reduce

1)reduce:相当与迭代;
[].reduce(function(previous,current,index,array){
return previous * current;//相当与做阶乘;
})

var arr = [6,3,4,1];
arr.reduce(function(pre,current){
return pre * current;
})
previous + current = previous
6 + 3 = 9;
9 + 4 = 13;
13 + 1 = 14;

模拟reduce:
if (Array.prototype.reduce === undefined)
Array.prototype.reduce = function(fun){
if(this === void 0 || this === null) throw new TypeError()
var t = Object(this), len = t.length >>> 0, k = 0, accumulator
if(typeof fun != 'function') throw new TypeError()
if(len == 0 && arguments.length == 1) throw new TypeError()

if(arguments.length >= 2)
accumulator = arguments[1]
else
do{
if(k in t){
accumulator = t[k++]
break
}
if(++k >= len) throw new TypeError()
} while (true)

while (k < len){
if(k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t)
k++
}
return accumulator
}