JavaScript——数组的归并方法

发布时间 2024-01-05 16:18:46作者: 周祥宇

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
}, [])

欢迎评论,欢迎纠错,我们一起成长!
xyzh.work@foxmail.com