Jump to content

explanation needed regarding JavaScript Array Object


kiedis

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 comment
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 comment
Share on other sites

  • 4 weeks later...

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
×
×
  • Create New...