I am practicing with arrays and loops and am running into an issue with this piece of code. When printing out, it doesn't print out all of the names. It only prints:
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]); }
What am I doing wrong?
This is a bit weird way of looping, but you're practicing, so fine. However, your code works properly. Here is a demo:
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]); }
This works:
var names = ["Paul", "Becky", "Aubrie", "Zeus", "Athena"];
for (var i = 0; names.length > i; i++) {
console.log("I know someone called " + names[i]);
}
more compact
var names = ["Paul", "Becky", "Aubrie", "Zeus", "Athena"]; for (var i in names) { document.write("I know someone called " + names[i] + "<br>"); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.