简体   繁体   中英

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>"; instead of x="The number is " + i + "<br>";

The first code snippet x=x+"The number is " + i + "<br>"; appends each new message to the end of the string x ; the second one x="The number is " + i + "<br>"; simply replaces x with the new message.

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:

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:

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>" . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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