UNPKG

zts-js-polyfill

Version:

22 lines (20 loc) 670 B
// 将自己定义的方法添加到数组原型上 Array.prototype.myReduce = function(func, b) { //获取传递过来的两个参数,第一个参数是在每一项上调用的函数, //第二个参数为可选的基础值 for (var i = 0; i < this.length; i++) { //前一个值 b,当前值 this[i],项的索引i,数组对象this func(b, this[i], i, this) b += this[i] } //返回最后的结果 return b } ///////////////// //调用 var arr = [1, 2, 3, 4] var sum = arr.myReduce((prev, next) => { console.log('pre:', prev, 'next:', next) return prev + next; }, 1000) console.log(sum)