我的代码只打印数组的最后一个值

my code only prints the last value of the array

我创建了一个变量并使用 push 属性添加了新值,但是当 for-loop 逐一调用它时,它只打印最后一个值(名称),即 "Pranav"。你能帮我知道如何修复它并逐一打印所有值吗?

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 属性 的值。您可能是想追加而不是替换。所以...

改变这个:

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

对此:

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

问题在于,在这一行中,您将 innerHTML 设置为一个名称,因此每次都会被覆盖:

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

尝试将其更改为追加,或类似的东西:

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

当用于字符串时,+ 运算符称为 concatenation 运算符。 += 因此,将意味着追加先前的值。

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