【发布时间】:2017-03-04 12:11:27
【问题描述】:
我正在编写一个程序来计算 24、36、48 和 60 个月的每月贷款还款额。
我想知道我应该调用循环内部还是外部的函数,然后将输出放入循环中?
我猜函数应该进入循环,因为我调用了 函数 4 次,这样它就会循环遍历每个函数? 或者,它会只循环每个函数 4 次吗?
我还希望循环从 24 开始,每次递增 12,直到达到 60。所以我在 for 循环代码中试了一下,但我不确定。
代码:
<!DOCTYPE html>
<html>
<head>
<title>Chapter 6 Assignment 2</title>
<meta charset="UTF-8">
<style>
body{
background-color: grey;
}
</style>
</head>
<body>
<script type="text/javascript">
vehiclePrice = +prompt("What is the vehicle price? ","");
moneyDown = +prompt("How much are you putting down? ","");
interestRate = +prompt("What is the interest rate for your loan? ","");
numMonths;
loanAmount = vehiclePrice - moneyDown;
MonthlyRate = interestRate / 1200;
function monthly_due(interestRate, numMonths, loanAmount){
var base = Math.pow(1 + interestRate, numMonths);
var payment = loanAmount * interestRate / (1 - (1/base));
return payment
}
//make function calls here? Function needs to be called 4 times for example
//monthly_due(interestRate, 24, loanAmount);
//monthly_due(interestRate, 36, loanAmount);
//monthly_due(interestRate, 48, loanAmount);
//monthly_due(interestRate, 60, loanAmount);
for (var count = 24; count <= 60; count += 12){
document.write("Number of months: ");
document.write("<br>");
document.write(count); // to display 24, and 12 each time it loops?
document.write("<br>");
doucment.write("Monthly Payment: ");
document.write("<br>");
document.write(monthly_due(interestRate, 24, loanAmount); //make function call here?
}
【问题讨论】:
-
您的所有变量都应使用
var、let或const声明。在最后一行调用monthly_due 时,您总是超过24 个月,而不是计数 -
你的代码中有很多错误的code smells;上述缺少声明大部分变量,使用脚本标签上的
type属性并使用document.write。阅读我写的关于 spotting bad JavaScript tutorials 的这篇文章,您可能会受益。 -
另外,使用unary plus 转换提示中的答案很好,但您可能希望在转换之前测试提示返回的值,如果用户按下取消按钮,它将返回
null。+null将强制转换为0,因此您无需知道它们已取消,而是继续使用零进行计算。也就是说,在生产就绪版本中,您可能希望使用input框并检查它们是否已填写而不是提示。
标签: javascript html loops