[英]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.我被指示在 object 本身中创建一个方法,以便更轻松地存储值。 However, I will need the function again in another code.但是,我需要在另一个代码中再次使用 function。 To avoid repetition I have created a separate function, calculateTip, and a separate for loop to iterate over the bills within the John object.为了避免重复,我创建了一个单独的 function、calculateTip 和一个单独的 for 循环来遍历 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...]) (因此 finalBills 数组应该显示以下的总和:[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
:当你使用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.