我对JavaScript很陌生,但我的任务是创建一个脚本来计算汽车贷款的每月付款。我做了一个函数,接受贷款金额,贷款期限和利率的输入,以便我可以计算具体的每月付款。我还希望能够向用户显示每月付款,如果他们获得更长时间的贷款,如36,48或60个月。我使用循环来改变贷款长度的变量来做到这一点,但我无法弄清楚如何让函数接受循环创建的不同长度。也许我说这一切都错了。
这是我到目前为止所做的:
function payment(monthly_interest_rate, loan_amount, loan_length) {
var base = Math.pow(1 + monthly_interest_rate, loan_length);
var payment = loan_amount * monthly_interest_rate / (1 - (1 / base));
return payment;
}
var vehicle_price = parseInt(prompt("How much does the vehicle cost?"));
var down_payment = parseInt(prompt("How much is the down payment?"));
var interest_rate = parseFloat(prompt("What is the interest rate?"));
var loan_amount = vehicle_price - down_payment;
var monthly_interest_rate = interest_rate / 1200;
var loan_length = parseInt(prompt("How many months is the loan?"));
document.write("Vehicle price: $" + vehicle_price + "<br>");
document.write("Down payment: $" + down_payment + "<br>");
document.write("Interest rate: " + interest_rate + "%" + "<br>");
document.write("Loan Amount: $ " + loan_amount + "<br>");
document.write("Number of months: " + "<br>");
for (loan_length = 24; loan_length < 61; loan_length += 12) {
document.write(loan_length + "<br>");
}
var monthly_payment = payment(monthly_interest_rate, loan_amount, loan_length).toFixed(2);
document.write("<br>" + "Monthly payment");
document.write("<br>" + "$" + monthly_payment);
<h1>Loan Calculator</h1>
答案 0 :(得分:0)
这就是你要找的东西吗?
function payment(monthly_interest_rate, loan_amount, loan_length) {
var base = Math.pow(1 + monthly_interest_rate, loan_length);
return loan_amount * monthly_interest_rate / (1 - (1 / base));
}
var vehicle_price = 1000
var down_payment = 200
var interest_rate = 1.5
var loan_amount = vehicle_price - down_payment;
var monthly_interest_rate = interest_rate / 1200;
var loan_length = 12
document.write("Vehicle price: $" + vehicle_price + "<br>");
document.write("Down payment: $" + down_payment + "<br>");
document.write("Interest rate: " + interest_rate + "%" + "<br>");
document.write("Loan Amount: $ " + loan_amount + "<br>");
var range = [12,24,36,48]
for (x=0; x < range.length; x++) {
document.write("Loan for " + range[x] + " months: <br>");
var monthly_payment = payment(monthly_interest_rate, loan_amount, range[x]).toFixed(2);
document.write(monthly_payment + "<br>");
}
<h1>Loan Calculator</h1>