Javascript While循环中不需要的输出

时间:2016-02-16 09:01:23

标签: javascript while-loop

我得到以下代码的输出为n = 3,x = 6 但我需要输出

n = 1, x = 1
n = 2, x = 3
n = 3, x = 6

有人可以帮助我在代码中添加其他内容吗?

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>

    function myFunction() {
        var n = 0;
        var x = 0;
        while (n < 3) {
            n++;
            x += n;
        }
        document.getElementById("demo").innerHTML = "n = " + n + ", " + "x = " + x;
    }

</script>

</body>
</html>

@Jai下面的例子类似,

function myFunction() {
    var text = "";
    var i = 0;
    while (i < 10) {
        text += "<br>The number is " + i;
        i++;
    }
    document.getElementById("demo").innerHTML = text;
}

输出

The number is 0  
 The number is 1
  ...

3 个答案:

答案 0 :(得分:1)

function myFunction() {
    var n = 0;
    var x = 0;
    while (n < 3) {
        n++;
        x += n;

    document.getElementById("demo").innerHTML += 
    "n = " + n + ", " + "x = " + x;
    }

}

你必须&#34;添加&#34;内部html。所以,把&#34; + =&#34;并在循环内。

答案 1 :(得分:1)

连接innerHTML并将其置于循环中:

document.getElementById("demo").innerHTML += 
"n = " + n + ", " + "x = " + x;

} // <---end of while

答案 2 :(得分:0)

您的代码执行while循环3次,每次更新n和x的值。但是因为您在while循环之外写入输出,所以只能看到最后的值。您需要在while循环中放置一行显示变量。