我正在练习数组和循环,并遇到了这段代码的问题。打印时,它不会打印出所有名称。它只打印:
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]);
}
我做错了什么?
答案 0 :(得分:2)
这是一种有点奇怪的循环方式,但你正在练习,很好。但是,您的代码正常工作。这是一个演示:
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;
答案 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]);
}
答案 2 :(得分:0)
更紧凑
var names = ["Paul", "Becky", "Aubrie", "Zeus", "Athena"];
for (var i in names) {
document.write("I know someone called " + names[i] + "<br>");
}