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

时间:2015-04-17 05:14:30

标签: javascript function for-loop push

我创建了一个变量并使用push属性添加了新值,但是当for循环逐个调用它时,它只打印最后一个值(名称),即" 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>"
    };
};

3 个答案:

答案 0 :(得分:0)

每次循环都会替换innerHTML属性的值。你可能意味着追加而不是替换。所以......

改变这个:

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

到此:

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

答案 1 :(得分:0)

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

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

尝试将其更改为附加或类似内容:

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

答案 2 :(得分:-1)

在字符串上使用时,+运算符称为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