Jump to content

Looping Arrays


bmjaczynski
 Share

Recommended Posts

For this example:

var fruits, text, fLen, i;
fruits = ["Banana", "Orange", "Apple", "Mango"];
fLen = fruits.length;

text = "<ul>";
for (i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

why does the last line output as </ul> instead of <ul></ul>? Since it is using the += operator.

Link to comment
Share on other sites

Yes it's correct code, but I'm new to coding so it seems my logic is flawed when I try to break it down and I'm not sure why. Why isn't the variable 'text' being looped since it's looping what looks to me like:

for (i = 0; i < fLen; i++) {
    text += "<li>" + fruits[i] + "</li>";     // "<ul>" = "<ul>" + "<li>" + fruits[i] + "</li>"
}

Same for the last line:

text += "</ul>";  // "<ul>" = "<ul>" + "</ul>"

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...