Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I made a variable and added new values with the push attribute but when the for-loop calls it one-by-one it only prints the last value(name) that is "Pranav". Can you help me to know how to fix it and print all the values one-by-one.

function tryme() {
    var names = new Array();
    names.push("Bhavesh", "Ajay", "Rahul", "Vinod", "Bobby", "Pranav");
    var tryit = document.getElementById("tryit");
    for (i = 0; i < names.length; i++) {
        tryit.innerHTML = "The values are " + names[i] + " . <br>"
    };
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
141 views
Welcome To Ask or Share your Answers For Others

1 Answer

You are replacing the value of the innerHTML property each time through the loop. You probably mean to append instead of replace. So...

Change this:

tryit.innerHTML = "The values are " + names[i] + " . <br>"

to this:

tryit.innerHTML += "The values are " + names[i] + " . <br>"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...