0

我是 JavaScript 新手,正在尝试更多地了解它可以做什么以及如何使用它。

是否可以作为计算结果返回多个结果?

我正在为一个班级项目做一个计算器。我想做的是在我的页面上返回 3 个值:

Interest rate

total amount borrowedmonthly 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; 

}

如果有人能指出我正确的方向,那就太好了!

4

2 回答 2

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>
于 2012-05-08T21:09:47.677 回答
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/

于 2012-05-08T21:11:21.703 回答