简体   繁体   中英

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

I have the following code which calculates a tip percentage that is relative to the amount of the bill. I was instructed to create a method within the object itself to store the values much easier. However, I will need the function again in another code. To avoid repetition I have created a separate function, calculateTip, and a separate for loop to iterate over the bills within the John object.

I have figured out how to calculate the separate tips and store those values within the tips array.

Now I would like to take the original bill amount and add them to its corresponding tip and push that to the array.

(So that the finalBills array should show the sums of: [142.6, 57.60 etc...])

Here is what I have come up with so far...

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)

When you use toFixed you get a string instead of a number, try using parseFloat , also if the method is to be in the object you could create a 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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