Jump to content

explanation needed regarding JavaScript Array Object

Recommended Posts

hi. learnign JavaScript from tutorial provided at http://www.w3schools.com/js/default.asp In JavaScript Array Object section, I was presented with this script: <script>var i;var mycars = new Array();mycars[0] = "Saab";mycars[1] = "Volvo";mycars[2] = "BMW";for (i=0;i<mycars.length;i++){document.write(mycars + "<br>");}</script> I realize that this code says to increase integer value by 1 as long as i<mycars.length But i don't get what is mycars.length in this case? The length of "mycars" (6 characters in this case?) I experimented by adding additional variables: <script>var i;var mycars = new Array();mycars[0] = "Saab";mycars[1] = "Volvo";mycars[2] = "BMW";mycars[3] = "boeing";mycars[4] = "volga";mycars[5] = "airbus";mycars[6] = "tupolev";mycars[7] = "yak";for (i=0;i<mycars.length;i++){document.write(mycars + "<br>");}</script> and i hoped that this addition of new variables will disrupt this function but no, all new variables were displayed properly when i clicked "submit code". Then i changed the function in this place:for (i=0;i=mycars.length;i++) and then immediately my internet browser froze and i had to close it down. So, what kind of length does the mycars.length indicate here and why it's so important that i< mycars.length here? just can't get it :D

Link to post
Share on other sites

mycars.lengthis the number of elements in the array object. The goal of the loop is to cycle through all the elements. So it starts with mycars[0] and loops until it reaches the element before mycars[mycars.length]. i=mycars.length uses the assignment operator ( = ), not the test-for-eqality operator ( == ) so the value never changes. i always = mycars.length so the loop never ends. That's why you crashed.

Link to post
Share on other sites
  • 4 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...