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);
  • 相关阅读:
    代码校验工具 SublimeLinter 的安装与使用
    java中写sql语句的小小细节
    搭建Hexo博客并部署到Github
    更改npm全局模块和cache默认安装位置
    笔记本连接老式显示器(VGA线+HDMI接口)
    用JSON-server模拟REST API
    使用 Feed43
    Coding.net+Myeclipse 2014 Git配置
    line-height 属性
    border-style 属性
  • 原文地址:https://www.cnblogs.com/richard1015/p/9675267.html
Copyright © 2011-2022 走看看