简体   繁体   中英

For loop only outputs last iteration

I am new to Javascript and am just playing around trying to print a simple for loop to the HTML.

HTML:

<div id="hello"</div>

JS :

var text="";

for (var i=0;i<10;i++) {
    document.getElementById("hello").innerHTML=text+i;
}

My problem is that this code only outputs the last iteration '9', and not '0123456789' which is what I want.

Now if i do document.write it prints out the numbers fine but I heard this is bad practice so I just want to do it the correct way.

Thanks

It would be better to build your text content first and insert it into HTML element once (to save some time):

var text="";

for (var i=0;i<10;i++) {
    text += i;
}

document.getElementById("hello").innerHTML = text;

You should use the addition assignment operator += that adds a value to a variable, so you're just missing + before = in :

document.getElementById("hello").innerHTML += text+i;

NOTE : Use textContent instead of innerHTML because you're appending just a text, check example bellow.


 var text=""; for (var i=0;i<10;i++) { document.getElementById("hello").textContent += text+i; } 
 <div id="hello"></div> 

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