js 数组求和reduce.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>reduce</title>
</head>
<body>
<script>
    /*知识点:
    * 定义和用法
    reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
    reduce() 可以作为一个高阶函数,用于函数的组成。
    注意: reduce() 对于空数组是不会执行回调函数的。
    * 语法
    array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
    * 参数
    参数 描述
    function(total,currentValue, index,arr)    必需。用于执行每个数组元素的函数。
    函数参数:
    参数 描述
    total  必需。初始值, 或者计算结束后的返回值。
    currentValue   必需。当前元素
    currentIndex   可选。当前元素的索引
    arr    可选。当前元素所属的数组对象。
    initialValue   可选。传递给函数的初始值
    * 参考:https://www.runoob.com/jsref/jsref-reduce.html*/
    // 示例1.
    let numbers = [1, 2, 3, 4];

    function sum1(total, num) {
        /*此函数用于,数组元素求和。*/
        return total + num;
    }

    console.log(numbers.reduce(sum1));
    // 10

    // 示例2.封装成一个函数。
    function sum(arr) {
        /*此函数用于,数组求和。*/
        return arr.reduce(function (total, currentValue, currentIndex, arr) {
            return total + currentValue;
        });
    }

    console.log(sum(numbers));  // 10

    // 示例3.“四舍五入”后,求和。
    numbers = [1.5, 2.3, 3.1, 4.7];

    function sum2(total, num) {
        /*此函数用于,数组元素“四舍五入”后,求和。*/
        return total + Math.round(num);
    }

    console.log(numbers.reduce(sum2, 0));
    // 12
    console.log(numbers.reduce(sum2, 1));
    // 13
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_42193179/article/details/91437983