var minimumPayment = 10;
var originalBalanceOption1 = 1000;
var interestRate = 0.15;
var initMonth = 0;
while (initMonth < 12) {
var payment = minimumPayment * originalBalanceOption1 / 100;
var interest = ((interestRate / 12) * originalBalanceOption1 / 100);
var principal = payment - interest;
var newBalance = originalBalanceOption1 - principal;
document.write(initMonth.toFixed(2) + '----' + payment.toFixed(2) + '----' + principal.toFixed(2) + '----' + newBalance.toFixed(2));
document.write('<br>');
initMonth++;
}
我正在构建此财务计算器。我是javascript新手。我正在尝试循环,但是我仅获得该行的第一个值。
答案 0 :(得分:0)
您的代码存在的问题是,您不会在循环的下一个迭代中携带新的余额。相反,您可以基于 initial 余额在每个迭代中开始计算。
只需对代码进行最少的更改,即可使其工作如下:
var minimumPayment = 10;
var originalBalanceOption1 = 1000;
var interestRate = 0.15;
var initMonth = 0;
var newBalance = originalBalanceOption1; // Work with newBalance, not with original
while (initMonth < 12) {
var payment = minimumPayment * newBalance / 100;
var interest = ((interestRate / 12) * newBalance / 100);
var principal = payment - interest;
newBalance = newBalance - principal;
document.write(initMonth.toFixed(2) + '----' + payment.toFixed(2) + '----' + principal.toFixed(2) + '----' + newBalance.toFixed(2));
document.write('<br>');
initMonth++;
}
但是我建议您:
for
循环而不是while
循环document.write
。如果仅出于查看代码进度的目的,请使用console.log
。如果要在网页上显示信息,请使用其他DOM方法。console.log
打印该数组或将其用于网页上的表示。这是一个实现:
function getPayments(minimumPaymentPct, originalBalance, interestRate) {
const payments = [];
for (let month = 0, balance = originalBalance; month < 12; month++) {
const payment = minimumPaymentPct * balance;
const interest = ((interestRate / 12) * balance / 100);
const principal = payment - interest;
balance -= principal;
payments.push({
payment: +payment.toFixed(2),
principal: +principal.toFixed(2),
balance: +balance.toFixed(2)
});
}
return payments;
}
const payments = getPayments(0.10, 1000, 0.15);
console.log(payments);