js怎么实现Array的reduce函数?

墨色风雨
浏览 764回答 2
2回答

蝴蝶刀刀

if (!Array.prototype.reduce) {&nbsp; Array.prototype.reduce = function(callback /*, initialValue*/) {&nbsp; &nbsp; 'use strict';&nbsp; &nbsp; if (this === null) {&nbsp; &nbsp; &nbsp; throw new TypeError('Array.prototype.reduce called on null or undefined');&nbsp; &nbsp; }&nbsp; &nbsp; if (typeof callback !== 'function') {&nbsp; &nbsp; &nbsp; throw new TypeError(callback + ' is not a function');&nbsp; &nbsp; }&nbsp; &nbsp; var t = Object(this), len = t.length >>> 0, k = 0, value;&nbsp; &nbsp; if (arguments.length == 2) {&nbsp; &nbsp; &nbsp; value = arguments[1];&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; while (k < len && !(k in t)) {&nbsp; &nbsp; &nbsp; &nbsp; k++;&nbsp;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (k >= len) {&nbsp; &nbsp; &nbsp; &nbsp; throw new TypeError('Reduce of empty array with no initial value');&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; value = t[k++];&nbsp; &nbsp; }&nbsp; &nbsp; for (; k < len; k++) {&nbsp; &nbsp; &nbsp; if (k in t) {&nbsp; &nbsp; &nbsp; &nbsp; value = callback(value, t[k], k, t);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return value;&nbsp; };}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java