目录
1、概念
- 1、概念
- 2、MDN链接地址
- 3、代码
-
- 3.1、功能函数
- 3.2、函数调用
reduce()方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
2、MDN链接地址MDN - reduce
3、代码 3.1、功能函数Array.prototype.myreduce = function(callback, initialValue) { const len = this.length; let k = 0; // 如果this的长度等于0, // 抛出错误 if (len == 0) { throw new TypeError('this is null or not defined'); }; // 如果callback的类型不是function函数类型, // 抛出错误 if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); }; // 如果initialValue的值为undefined // 拿出this里面的第一个值作为累加值 // 同时把k++ , // 因为this[k]需要返回两个值 // 第一个值是initialValue // 第二个值是this[k] // 如果initialValue的值不为undefined // 直接返回initialValue和this[k] // 此时this[k] => k = 0; if (initialValue === undefined) { initialValue = this[k++]; }; // 如果initialValue的值不是数字或者字符串类型的数字, // 抛出错误 if (!/^(-?\d+)(\.\d+)?$/.test(initialValue)) { throw new TypeError(initialValue + ' is not number'); }; while (k < len) { // 如果this中的值不是数字或者字符串类型的数字, // 抛出错误 if (!/^(-?\d+)(\.\d+)?$/.test(this[k])) { throw new TypeError(this[k] + ' is not number'); }; // 如果k的值在this中有对应的下标, // 就继续执行, // 否则退出 if (k in this) { // Number(initialValue)把字符串类型的数字转为纯数字 // Number(this[k])把字符串类型的数字转为纯数字 // 回调函数的作用是将循环出来的数据返回到外面 initialValue = callback.call(undefined, Number(initialValue), Number(this[k]), k, this); }; k++; }; return initialValue; };3.2、函数调用
// 纯数组求和 let sumNumF = function(item, num) { return item + num; }, dataNum = ['2', 3.1, '2.2']; console.log(dataNum.myreduce(sumNumF, '3.1')); // 10.399999999999999 // 数组对象求和 function sumObjF(item, num) { // Math.round(num)四舍五入 return item + Math.round(num); }; let sumObj = [{ id: 1, value: 2 }, { id: 2, value: 1 }, { id: 3, value: '1.4' }, { id: 4, value: '2.6' }]; console.log(sumObj.map((item) => { return item.value; }).myreduce(sumObjF)); // 7