YBFACC / blog

仅记录个人学习使用
3 stars 0 forks source link

reduce、forEach手写 #45

Open YBFACC opened 2 years ago

YBFACC commented 2 years ago

reduce、foEach手写

Array.prototype._reduce = function (fn, init) {

  //类型检测

    let sum = init === undefined ? 0 : init
    const list = this

    for (let i = 0; i < list.length; i++) {
        sum = fn.call(this, sum, list[i], i, list)
    }

    return sum
}

console.log(
    [1, 2, 3]._reduce(function (pre, curr) {
        return pre + curr
    })
)

关于forEach能不能提前结束循环:不能。

我对此的理解:执行的回调函数中,不能控制父级函数的执行。只能结束当前的函数调用栈,然后将执行权交给父级。

let a = [1, 2, '11']

Array.prototype._forEach = function (fn, thisArg) {
    //类型判断

    const list = this
    for (let i = 0; i < list.length; i++) {
        fn.call(this, list[i], i, arr)
    }
}

function n() {
    a._forEach((v, i) => {
        console.log(v)
        return
    })
}
n()