使用for循环计算兴趣

时间:2015-06-26 01:09:37

标签: javascript

好的,所以我准备制作一个计算器来计算一段时间内对本金的兴趣,例如10年。本金是100,000,利率是.08%到目前为止,我的代码工作并没有错误,但它只显示第一年而不会显示其他9.我在这里看不到什么?

function interest(){
    var investment = 100000;
    var rate = .08;
    var text = "";
    var amount = 100000 * (1.0 + .08 * 1);
    var year = new Array(12);
    var i ;
    for (i=0; i < year.length; i++) {
        text += "The total to date is " + "$" + i + "<br>";
        year[i] = i+investment;
    }
    document.getElementById("demo").innerHTML = text;
    document.getElementById("demo").innerHTML = amount;
}

2 个答案:

答案 0 :(得分:1)

我对您的计算不确定,但是您没有得到其他9的原因是,当您使用innerHTML时,您会覆盖当前。因此,在第一行中,您将innerHTML设置为文本,但在此之后,您将其覆盖为金额,这就是您不看多年的原因。

document.getElementById("demo").innerHTML = text + amount;

我猜你要做的事情就是下面的计算:

function interest(){
    var investment = 100000;
    var rate = .08;
    var text = "";
    var year = new Array(12);
    for (var i=1; i <= year.length; i++) {
        text += "The total will be in "+i+" years is " + "$" + (investment * ( 1 + (i * rate))) + "<br>";
    }
    document.getElementById("demo").innerHTML = text;
}

查看下面的演示:

http://jsfiddle.net/d6w7yefL/3

答案 1 :(得分:0)

删除第二行

document.getElementById(“demo”)。innerHTML = amount;

看到这个:

    var investment = 100000;
    var rate = .08;
    var text = "";
    var amount = 100000 * (1.0 + .08 * 1);
    var year = new Array(12);
    var i ;
    for (i=0; i < year.length; i++) {
    text += "The total to date is " + "$" + i + "<br>";
    year[i] = i+investment;
    }

    document.getElementById("demo").innerHTML = text;
    //document.getElementById("demo").innerHTML = amount;

http://jsfiddle.net/dshun/w9x7zk5d/