我是JavaScript新手,并尝试详细了解它可以做什么以及如何使用它。
是否可以通过计算返回多个结果?
我正在研究一个班级项目的计算器。我想要它做的是在我的页面上返回3个值:
Interest rate
total amount borrowed
和
monthly repayment
到目前为止,我已经设法让它在页面上的div中显示每月还款,但我希望能够通过一次计算显示页面上的所有3。
这可能吗?
这是我到目前为止所提出的:
HTML:
<p><input type="button" onclick="main();" value="Calculate"></p>
JavaScript的:
function main()
{
var userInput1 = 0;
var userInput2 = 0;
var displayResult;
userInput1 = document.getElementById("loan_amount").value;
userInput1 = parseFloat(userInput1);
userInput2 = document.getElementById("loan_term").value;
userInput2 = parseFloat(userInput2);
displayResult = calcLoan(userInput1,userInput2);
document.getElementById("Result1").innerHTML=displayResult;
}
function calcLoan(userInput1,userInput2)
{
var interest =0;
if (userInput1 <1000)
{
alert("Please enter a value above £1000")
}
else if (userInput1 <= 10000)
{
interest = 4.25 + 5.5;
}
else if (userInput1 <= 50000)
{
interest = 4.25 + 4.5;
}
else if (userInput1 <= 100000)
{
interest = 4.25 + 3.5;
}
else
{
interest = 4.25 + 2.5;
}
var totalLoan = 0;
totalLoan = userInput1 +(userInput1*(interest/100))*userInput2;
var monthlyRepayment = 0;
var monthly;
monthlyRepayment = totalLoan/(userInput2*12);
monthly=monthlyRepayment.toFixed(2);
alert("Interest Rate = " + interest + "%" +" "+"Total Loan amount = " + "£"+ totalLoan +" "+ "Your monthly repayment is = " + " " + "£"+ monthly);
return monthly;
}
如果有人能指出我正确的方向,那就太好了!
答案 0 :(得分:1)
您可以使用多个自定义字段创建变量,并在函数之间传递它们。所以,你的函数应该是这样的:
function main()
{
...
displayResult = calcLoan(userInput1,userInput2);
document.getElementById("Result1").innerHTML = displayResult.interest;
document.getElementById("Result2").innerHTML = displayResult.totalLoan;
document.getElementById("Result3").innerHTML = displayResult.monthly;
}
function calcLoan(userInput1,userInput2)
{
...
alert("Interest Rate = " + interest + "%" +" "+"Total Loan amount = " + "£"+ totalLoan +" "+ "Your monthly repayment is = " + " " + "£"+ monthly);
var result;
result.interest = interest;
result.totalLoan = totalLoan;
result.monthly = monthly;
return result;
}
不要忘记添加ID为Result1,Result2和Result3的div元素。
<div id="Result1"></div>
<div id="Result2"></div>
<div id="Result3"></div>
答案 1 :(得分:0)
尝试一些JavaScript OOP。函数可以很容易地返回多个值。有几种方法可以做到这一点。请尝试阅读:http://killdream.github.com/blog/2011/10/understanding-javascript-oop/和此:http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/