my code only prints the last value of the array

自古美人都是妖i 提交于 2021-02-02 10:01:30

问题


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

回答1:


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



回答2:


The problem is that on this line, you're setting the innerHTML equal to a single name, so it just gets overwritten each time:

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

Try changing it to append instead, or something similar:

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



回答3:


When used on strings, the + operator is called the concatenation operator. += thus, will mean to take append on previous value.

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

FIDDLE



来源:https://stackoverflow.com/questions/29690878/my-code-only-prints-the-last-value-of-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!