1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| Array.prototype.myReduce = function (cb, value) { if (value||value===0) { for(let i = 0; i < this.length; i++){ value = cb(value, this[i]) } } else { for (let i = 0; i < this.length - 1; i++) { value = cb(i === 0 ? this[i] : value, this[i + 1]) } } return value }
let arr1 = [1, 2, 3, 4, 5] let arr2 = [ {age:20}, {age:30}, {age:40} ] let result = arr2.myReduce(function (pre, next) { return pre+next.age },0) console.log(result)
|