问题
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