for循环打印出整个数组的问题

时间:2015-11-05 18:48:22

标签: javascript arrays for-loop

我正在练习数组和循环,并遇到了这段代码的问题。打印时,它不会打印出所有名称。它只打印:

I know someone called Athena

    var names = ["Paul", "Becky", "Aubrie", "Zeus", "Athena"];
    var x = 1;
    for (var i = 0; i < 5; i += x) {
        console.log("I know someone called " + names[i]);
    }

我做错了什么?

3 个答案:

答案 0 :(得分:2)

这是一种有点奇怪的循环方式,但你正在练习,很好。但是,您的代码正常工作。这是一个演示:

&#13;
&#13;
var names = ["Paul", "Becky", "Aubrie", "Zeus", "Athena"];
var x = 1;
for (var i = 0; i < 5; i += x) {
    document.write("<br/>I know someone called " + names[i]);
}
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这有效:

var names = ["Paul", "Becky", "Aubrie", "Zeus", "Athena"];

for (var i = 0; names.length > i; i++) {
    console.log("I know someone called " + names[i]);
}

spring docs

答案 2 :(得分:0)

更紧凑

var names = ["Paul", "Becky", "Aubrie", "Zeus", "Athena"];
    for (var i in names) {
        document.write("I know someone called " + names[i] + "<br>");
    }