简体   繁体   English

如何返回对象数组属性的总和而不是它们的double?

[英]How to return the sum of objects-array properties instead of their double?

I was making an expense tracker basic code (without ui, only the initial script), but i had a problem while trying to console.log the sum of the total spent money by the user, my code only doubles the spent money for each bought item so i decided to ask here for help. 我正在制作一个费用跟踪器的基本代码(没有ui,只有初始脚本),但是在尝试console.log时出现问题,用户记录了总花费,我的代码仅使每笔购买的花费翻了一番项目,所以我决定在这里寻求帮助。

The code: 编码:

//initial code

const account = {
    name: 'user',
    expenses: [],
    addExpense: function(description, amount) {
        account.expenses.push({
            description: description,
            amount: amount
        });
    },
    getAccountSummary: function() {
        let expenses = account.expenses;
        for (let i = 0; i < expenses.length; i++ ) {
            let value = expenses[i].amount + expenses[i].amount;
            console.log(value);
        }
    }
}

//output calls

account.addExpense('Milk', 8);
account.addExpense('Netflix', 30);
account.addExpense('Steam summer sale', 26);
account.addExpense('Coffee', 4);
console.log(account.getAccountSummary());

The code always logs this values below: 代码始终在以下记录此值:

16
60
52
8

which are actually the double of the input values (8, 30, 26, 4). 实际上是输入值(8、30、26、4)的两倍。

The output i'm looking for is the sum of all of those value which is in this case: 我正在寻找的输出是所有这些值的总和,在这种情况下:

68

Hope my question was clear. 希望我的问题清楚。

When you want a value that is based on items in an array, then you should be looking at reduce 当您想要一个基于数组中项目的值时,您应该考虑reduce

const account = {
    name: 'user',
    expenses: [],
    addExpense: function(description, amount) {
        account.expenses.push({
            description: description,
            amount: amount
        });
    },
    getAccountSummary: function() {
       return account.expenses.reduce((acc,{amount}) => acc+amount,0);
    }
}

In your getAccountSummary 在您的getAccountSummary中

Use 采用

let value = 0;
for (let i = 0; i < expenses.length; i++ ) {
     value += expenses[i].amount ;   
     console.log(value); 
}

Hope it will help you. 希望对您有帮助。

expenses[i].amount is been added 2 times at let value = expenses[i].amount + expenses[i].amount; expenses[i].amount加2倍,以expenses[i].amount let value = expenses[i].amount + expenses[i].amount; , that's why is been doubled. ,这就是为什么被加倍的原因。

If you want to print the sum inside the getAccountSummary , you can do something like this: 如果要在getAccountSummary打印总和,则可以执行以下操作:

  getAccountSummary: function() {
      const expenses = account.expenses;
      let value = 0
      for (let i = 0; i < expenses.length; i++ ) {
          value += expenses[i].amount;
      }
      console.log(value);
  }

But if you want to return the sum on getAccountSummary so you can print it (which seems more reasonable), then you could do this: 但是,如果您想在getAccountSummary上返回总和,以便可以打印它(这似乎更合理),则可以这样做:

  getAccountSummary: function() {
      const expenses = account.expenses;
      let value = 0
      for (let i = 0; i < expenses.length; i++ ) {
          value += expenses[i].amount;
      }
      return value;
  }

And you should be able to call console.log(account.getAccountSummary()); 并且您应该能够调用console.log(account.getAccountSummary());

You can use forEach() to iterate over expenses as well. 您也可以使用forEach()迭代费用。

The main issue was that you were logging the values directly, instead of returning them for later logging. 主要问题是您是直接记录值,而不是返回它们以供以后记录。

Also, there's no need to use the "function" keyword in modern Javascript. 另外,在现代Javascript中也无需使用“ function”关键字。

Here's my solution, gives the expected output. 这是我的解决方案,给出了预期的输出。

const account = {

    name: 'user',
    expenses: [],

    addExpense(description, amount) {
        account.expenses.push({
            description: description,
            amount: amount
        });
    },

    getAccountSummary() {

        return account.expenses.reduce((result, expense) => result + expense.amount, 0)
    }
}

//output calls

account.addExpense('Milk', 8);
account.addExpense('Netflix', 30);
account.addExpense('Steam summer sale', 26);
account.addExpense('Coffee', 4);
console.log(account.getAccountSummary()); // 68

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM