简体   繁体   English

JavaScript for循环错误

[英]Javascript for-loop error

For example, I have the following code: 例如,我有以下代码:

<script>
    function myFunction()
    {
        var x="";
        for (var i=0;i<5;i++)
        {
            x=x+"The number is " + i + "<br>";
        }
        document.getElementById("demo").innerHTML=x;
    }
</script>

My question is, why x=x+"The number is " + i + "<br>"; 我的问题是,为什么x=x+"The number is " + i + "<br>"; instead of x="The number is " + i + "<br>"; 而不是x="The number is " + i + "<br>";

The first code snippet x=x+"The number is " + i + "<br>"; 第一个代码段x=x+"The number is " + i + "<br>"; appends each new message to the end of the string x ; 将每个新消息追加到字符串x的末尾; the second one x="The number is " + i + "<br>"; 第二个x="The number is " + i + "<br>"; simply replaces x with the new message. 只需将x替换为新消息。

Presumably the first one is being used so that all the output will be shown at once, as opposed to just the last line that was displayed. 大概是第一个被使用,因此所有输出将被立即显示,而不是仅显示最后一行。

One ( x=x+"The number is " + i + "<br>"; ) will append the output to x and output: 一个( x=x+"The number is " + i + "<br>"; )将输出附加到x并输出:

The number is 0<br>
The number is 1<br>
The number is 2<br>
The number is 3<br>
The number is 4<br>

The other one ( x="The number is " + i + "<br>"; ) will replace x on every iteration and output: 另一个( x="The number is " + i + "<br>"; )将在每次迭代和输出时替换x

The number is 4<br>

It appends one string to another string, building a longer string. 它将一个字符串附加到另一个字符串,构建一个更长的字符串。

So after the first iteration you have x equal to "The number is 0<br>" , after the second iteration the value of x is "The number is 0<br>The number is 1<br>" . 因此,在第一次迭代之后, x等于"The number is 0<br>" ,在第二次迭代之后, x值为"The number is 0<br>The number is 1<br>" And so on. 等等。

When you use :- 
       x=x+"The number is " + i + "<br>"
It will print whole  series numbers 
and When you use :-
        x="The number is " + i + "<br>"
It will print the last value of your series.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM