Array.prototype.reduce = function (callback, initValue) {
// 判断callback 是不是函数
if (typeof callback !== "function") {
throw new TypeError("callback is no function");
}
let arr = this;
let isInitValue= typeof initValue !== "undefined"
// 是否有初始值、
let base = isInitValue ? initValue : arr[0];
// 如果有初始值:数组下标0,没有则是1
let index = isInitValue ? 0 : 1;
let len = arr.length;
while (index < len) {
base = callback(base, arr[index++], index - 1, this);
}
return base;
};
let list = [{ name: "嘻嘻" }];
[{ name: "小红" }, { name: "小明" }].reduce((pre, next, index, arr) => {
pre.push(next);
return pre;
});
[1, 2, 3, 4, 5].reduce((pre, next, index) => {
return pre + next;
});
自定义reduce
最新推荐文章于 2025-05-14 14:41:23 发布