我的代码只打印数组的最后一个值 [英] my code only prints the last value of the array
本文介绍了我的代码只打印数组的最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个变量,并使用push属性添加了新值,但是当for循环一个接一个地调用它时,它仅显示最后一个值(名称)为"Pranav".您能帮我知道如何解决它,并一一打印所有值.
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>"
};
};
推荐答案
您每次在循环中都将替换 innerHTML
属性的值.您可能要附加而不是替换.所以...
You are replacing the value of the innerHTML
property each time through the loop. You probably mean to append instead of replace. So...
更改此:
tryit.innerHTML = "The values are " + names[i] + " . <br>"
对此:
tryit.innerHTML += "The values are " + names[i] + " . <br>"
这篇关于我的代码只打印数组的最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文