zoukankan      html  css  js  c++  java
  • JS Array.reduce 对象属性累加

    Array reduce() 方法  ,无非就是 计算数组元素 相加后的总和 ,看网上给的Demo 全是  [1,2,3,4,6].reduce 这种基本用法,

    本次我将使用 reduce 实现 数组对象中 具体属性 Price 累加   [{ name: 'apple',  price: 10 }, {  name: 'banana',   price: 9  } ];  

    方法 ChormeIE Firefox  SafariOpera 
    reduce() Yes 9.0 3.0 4 10.5
    参数描述
    function(total,currentValue, index,arr) 必需。用于执行每个数组元素的函数。
    函数参数:
    参数描述
    total 必需。初始值, 或者计算结束后的返回值。
    currentValue 必需。当前元素
    currentIndex 可选。当前元素的索引
    arr 可选。当前元素所属的数组对象。
    initialValue 可选。传递给函数的初始值

    普通 for 实现  和 reduce 实现对比

        let array = [
            {
                name: 'apple',
                price: 10
            }, {
                name: 'banana',
                price: 9
            }
        ];
    
        let sumprice = 0;
        for (let index = 0; index < array.length; index++) {
            const element = array[index];
            sumprice += element.price;
        }
        console.log('for example sumprice',sumprice);
    
        /* 
            reduce 语法实现
            total    必需。初始值, 或者计算结束后的返回值。
            currentValue    必需。当前元素
            currentIndex    可选。当前元素的索引
            arr    可选。当前元素所属的数组对象。
        */
        sumprice = array.reduce(function (total, currentValue, currentIndex, arr) {
            return total + currentValue.price;
        }, 0);
        console.log('for reduce sumprice',sumprice);
  • 相关阅读:
    k8spod资源的基础管理操作
    k8s名称空间资源
    bzoj5011: [Jx2017]颜色
    bzoj5010: [Fjoi2017]矩阵填数
    bzoj5008: 方师傅的房子
    bzoj5007: TCP协议
    bzoj5003: 与链 5004: 开锁魔法II 5005:乒乓游戏
    bzoj5020: [THUWC 2017]在美妙的数学王国中畅游
    bzoj5006: [THUWC2017 Bipartite]随机二分图
    bzoj4480: [Jsoi2013]快乐的jyy
  • 原文地址:https://www.cnblogs.com/richard1015/p/9675267.html
Copyright © 2011-2022 走看看