RJL1 Posted March 2, 2020 Share Posted March 2, 2020 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>"; Hi, Im a beginner trying to learn some javascript code and I cant seem to wrap my head around this. In the loop the text variable "<ul>" has "<li>" + fruits + "</li>" added to it becoming: text = "<ul>" + "<li>" + fruits + "</li"> inside the brackets. Why isnt the "<ul>" looped 4 times like the rest of the code? In my mind the output should be: < "<ul>" + "<li>" + fruits[0] + "</li>"; "<ul>" + "<li>" + fruits[1] + "</li>"; "<ul>" + "<li>" + fruits[2] + "</li>"; "<ul>" + "<li>" + fruits[3] + "</li>"; "</ul>" But it's not... Can someone explain? I hope it makes sense. Thanks in advance Link to comment Share on other sites More sharing options...
Ingolme Posted March 3, 2020 Share Posted March 3, 2020 Only the content inside the loop is repeated. This is what the string looks like on each iteration of the loop: text = "<ul>"; "<ul>" text += "<li>" + fruits[i] + "</li>"; "<ul><li>Banana</li>" text += "<li>" + fruits[i] + "</li>"; "<ul><li>Banana</li><li>Orange</li>" text += "<li>" + fruits[i] + "</li>"; "<ul><li>Banana</li><li>Orange</li><li>Apple</li>" text += "<li>" + fruits[i] + "</li>"; "<ul><li>Banana</li><li>Orange</li><li>Apple</li><li>Mango</li>" text += "</ul>"; "<ul><li>Banana</li><li>Orange</li><li>Apple</li><li>Mango</li></ul>" Since the string "<ul>" is not being appended inside the loop, it is not being repeated. 1 Link to comment Share on other sites More sharing options...
RJL1 Posted March 3, 2020 Author Share Posted March 3, 2020 Thanks alot Ingolme ! Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now