Changes

Jump to: navigation, search

JavaScript Arrays

583 bytes added, 14:39, 15 May 2007
Accessing the Elements of a JavaScript Array
Often, however, it is necessary to access each element in an array. While writing code to access each item one by one is accepbtable for an array with one a few items this becomes difficult for larger arrays. Fortunately thre are a couple of ways to ''loop'' through all the items in the array.
One way is to create a ''for loop'' (see [[JavaScript Flow Control and Looping]]) combined with the ''length'' property which contains the number of items in the specified array.The following example creates a for loop that will display each item in the array until the number of items in the array is reached: <pre> for (var i = 0; i < myColors.length; i++){ document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );} </pre> JavaScript provides an even easier way to access each element in an array using the ''for in'' syntax. This essentially performs the same functionas the above ''for loop'' but with a little less typing: <pre> for (i in myColors){ document.write ("myColor[" + i + "] = " + myColors[i] + "<br>" );} </pre>

Navigation menu