自己封装了JavaScript的数组的reduce、forEach、map方法方法,分别命名为myReduce、myForEach、myMap,代码如下
Array.prototype.myReduce = function(fn, prev) {
for (let i=0; i< this.length ; i++) {
if (typeof prev === 'undefined') {
prev = fn(this[i], this[i+1], i+1, this)
++i
} else {
prev = fn(prev, this[i], i, this)
}
}
return prev
}
Array.prototype.myForEach = function (fn) {
for (let i = 0; i < this.length; i++) {
fn(this[i], i)
}
}
Array.prototype.myMap = function (fn) {
let arr = []
for (let i = 0; i < this.length; i++) {
arr.push(fn(this[i], i))
}
return arr
}
其中myReduce的示例代码如下 1、第二个参数没有传值,这里每一步把4个参数都打印出来了
let total = [1, 2, 3, 4].myReduce((prev, currentValue, currentIndex, arr) => {
console.log(prev, currentValue, currentIndex, arr)
return prev + currentValue
})
console.log(total)
2、第二个参数有传值,这里每一步把4个参数都打印出来了
let total = [1, 2, 3, 4].myReduce((prev, currentValue, currentIndex, arr) => {
console.log(prev, currentValue, currentIndex, arr)
return prev + currentValue
}, 10)
forEach和map比较简单,大家可以自己在浏览器尝试一下