首页 小组 问答 话题 好文 素材 用户 唠叨 我的社区

[教程]数组的reduce方法

风轻yLv.1种子选手
2024-09-11 08:41:33
0
43

JavaScript的reduce和reduceRight的作用是通过顺序或逆序遍历数组,从而得到一个结果,原理如下:

function myReduce(execute, initValue) {
    const length = this.length
    let result

    for (let i = 0; i < length; i++) {
        if (i === 0) {
            const hasInitValue = initValue !== void 0,
                startIndex = hasInitValue ? 0 : 1

            i = startIndex
            result = execute(hasInitValue ? initValue : this[0], this[i], i, this)
        } else {
            result = execute(result, this[i], i, this)
        }
    }

    return result
}

function myReduceRight(execute, initValue) {
    const length = this.length
    let result

    for (let i = length - 1; i >= 0; i--) {
        if (i === length - 1) {
            const hasInitValue = initValue !== void 0,
                startIndex = hasInitValue ? length - 1 : length - 2

            i = startIndex
            result = execute(hasInitValue ? initValue : this[length - 1], this[i], i, this)
        } else {
            result = execute(result, this[i], i, this)
        }
    }

    return result
}

Array.prototype.myReduce = myReduce
Array.prototype.myReduceRight = myReduceRight

案例01——累加

array.myReduce(function (pre, cur, index, context) {
    return pre + cur
})

案例02——统计

array.myReduce(function (pre, cur, index, context) {
    if (pre[cur]) {
        pre[cur]++
    } else {
        pre[cur] = 1
    }

    return pre
}, {})

案例03——扁平化

array.myReduce(function (pre, cur, index, context) {
    if (Array.isArray(cur)) {
        pre.splice(pre.length, 0, ...cur)
    } else {
        pre.push(cur)
    }

    return pre
}, [])

案例04——去重

array.myReduce(function (pre, cur, index, context) {
    if (pre.includes(cur)) {
        return pre
    } else {
        pre.push(cur)
    }

    return pre
}, [])

案例05——最值

array.myReduce(function (pre, cur, index, context) {
    return Math.min(pre, cur)
})
风轻y
风轻y

41 天前

签名 :   43       0
评论
站长交流