Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

javascript - my code only prints the last value of the array

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...