【问题标题】:How to add the values of one array within a for loop to another and push it to an object如何将for循环中一个数组的值添加到另一个数组并将其推送到对象
【发布时间】:2019-10-01 04:04:38
【问题描述】:

我有以下代码计算相对于账单金额的小费百分比。我被指示在对象本身中创建一个方法来更容易地存储值。但是,我将在另一个代码中再次需要该函数。为了避免重复,我创建了一个单独的函数 calculateTip 和一个单独的 for 循环来遍历 John 对象中的账单。

我已经弄清楚如何计算单独的提示并将这些值存储在提示数组中。

现在我想将原始账单金额添加到相应的小费中,然后将其推送到数组中。

(因此 finalBills 数组应该显示以下各项的总和:[142.6, 57.60 etc...])

这是我到目前为止的想法......

var john = {
    patron: 'John',
    bills: [
        124,
        48,
        180,
        268,
        42
    ],
    tips: [],
    finalBills: []
}

function calculateTip(bill) {
    if (bill < 50) {
        percentage = (20 / 100);
    } else if (bill >= 50 && bill < 200) {
        percentage = (15 / 100);
    } else {
        percentage = (10 / 100);
    }
    return percentage * bill;
};

// console.log(john.bills.length);

for (var i = 0; i < john.bills.length; i++) {
    var bill = john.bills[i];
    console.log(bill);

    var tips = calculateTip(bill);
    var roundedTips = tips.toFixed(2);
    john.tips.push(roundedTips);
    console.log('These are the tip amounts: ', roundedTips)

    var finalBill = (roundedTips + bill);
    console.log('Final amounts: ', finalBill)
};

console.log(john)

【问题讨论】:

    标签: javascript arrays object for-loop


    【解决方案1】:

    当您使用toFixed 时,您会得到一个字符串而不是数字,请尝试使用parseFloat,如果方法要在对象中,您也可以 创建一个class:

    class Patron {
      constructor(patron, bills) {
        this.patron = patron;
        this.bills = bills;
        this.tips = [];
        this.finalBills = [];
      }
    
      calculateTip(bill) {
        let percentage;
        if (bill < 50) {
          percentage = (20 / 100);
        } else if (bill >= 50 && bill < 200) {
          percentage = (15 / 100);
        } else {
          percentage = (10 / 100);
        }
        return percentage * bill;
      }
    
      calculateFinalBill() {
        for (var i = 0; i < this.bills.length; i++) {
          var bill = this.bills[i];
          //console.log(bill);
          var tip = this.calculateTip(bill);
          var roundedTips = parseFloat(tip.toFixed(2));
          this.tips.push(roundedTips);
          //console.log('These are the tip amounts: ', roundedTips);
    
          var finalBill = (roundedTips + bill);
          //console.log('Final amounts: ', finalBill);
          this.finalBills.push(finalBill);
        }
      }
    }
    
    const john = new Patron('john', [124, 48, 180, 268, 42]);
    john.calculateFinalBill();
    console.log(john.finalBills);

    【讨论】:

    • 感谢您的帮助!我绝对理解您在这里所做的事情,并且可以解决问题。
    猜你喜欢
    • 2022-11-26
    • 2020-01-19
    • 2017-06-22
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 2019-01-19
    • 1970-01-01
    • 2020-08-23
    相关资源
    最近更新 更多