JS基礎知識之實現數組的reduce方法

JS基礎知識之實現數組的reduce方法

要點:

1、初始值不傳怎麼處理

2、回調函數的參數有哪些,返回值如何處理。

Array.prototype.myReduce = function(fn, initialValue) {
var arr = Array.prototype.slice.call(this);
var res, startIndex;
res = initialValue ? initialValue : arr[0];
startIndex = initialValue ? 0 : 1;
for(var i = startIndex; i < arr.length; i++) {
res = fn.call(null, res, arr[i], i, this);
}
return res;
}


分享到:


相關文章: