Javascript循环程序

时间:2013-07-10 23:49:36

标签: javascript loops

我正在尝试制作一个javascript贷款计算器程序。我似乎无法让我的循环在每一行上放置不同的数字。它假设显示从24个月,36个月,48个月和60个月开始支付的金额。我正在使用函数进行计算,但我总是得到24个月的结果。我知道你必须将nummonths改为36,48和60,但我不知道这样做。我认为循环会在每次循环时增加12个月。另外,您如何将数字格式化为货币?我最后得到了一个很长的数字。我尝试在calculate()上做parseFloat但是我收到了一个错误。 这是我的代码:

<html>
<BODY BGCOLOR="#FFC0CB">
<head>
<title>Chapter 6 Assignment 2</title>
</head>
<body>
<h1>Loan Calculator</h1>

<script type="text/javascript">
var vehicleprice = window.prompt("What is the vehicle price?", "");
var downpayment = window.prompt("What is the amount of the down payment?", "");
var annualinterest = window.prompt("What is the annual interest rate for the loan?", "");
var nummonths = 24
var loanamount = vehicleprice - downpayment
var monthlyinterest = annualinterest / 1200

vehicleprice = parseFloat(vehicleprice).toFixed(2);
downpayment = parseFloat(downpayment).toFixed(2);
loanamount = parseFloat(loanamount).toFixed(2);

function calculate()
             {
              var baseamount = Math.pow(1 + monthlyinterest, nummonths );
              return loanamount * monthlyinterest / (1 - (1/baseamount));
             }

document.write("Vehicle price: $" +vehicleprice+ "<br>");
document.write("Down payment: $" +downpayment+ "<br>");
document.write("Interest Rate: " +annualinterest+ "%<br>");
document.write("Loan Amount: $" +loanamount+ "<br>");

for (var count=2;count<=6;count+=1)
    {
    document.write(+calculate()+"<br />");
    }
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

好的,你必须自己增加nummonths。像这样......

for (var count=2;count<=6;count+=1)
{
    document.write(+calculate()+"<br />");
    nummonths += 12;
}

此外,您可以使用http://josscrowcroft.github.io/accounting.js/进行货币格式化。

答案 1 :(得分:2)

由于您没有使用count进行任何操作,因此您可以循环遍历nummonths

for (nummonths = 24; nummonths <= 60; nummonths += 12) {
    document.write(calculate() + "<br />");
}