簡體   English   中英

如何將 for 循環中一個數組的值添加到另一個數組並將其推送到 object

[英]How to add the values of one array within a for loop to another and push it to an object

我有以下代碼計算相對於賬單金額的小費百分比。 我被指示在 object 本身中創建一個方法,以便更輕松地存儲值。 但是,我需要在另一個代碼中再次使用 function。 為了避免重復,我創建了一個單獨的 function、calculateTip 和一個單獨的 for 循環來遍歷 John object 中的賬單。

我已經弄清楚如何計算單獨的提示並將這些值存儲在提示數組中。

現在我想獲取原始賬單金額並將它們添加到相應的小費中並將其推送到數組中。

(因此 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)

當你使用toFixed你得到一個字符串而不是一個數字,嘗試使用parseFloat ,如果方法是在 object 你可以創建一個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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM