17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sample: sample141.html<br />

<br />

var myArray = [[[['4th dimension']]]];<br />

console.log(myArray[0][0][0][0]); // Logs '4th dimension'.<br />

<br />

This code example is rather silly, but you get the idea that arrays can contain other<br />

arrays and you can access encapsulated arrays indefinitely.<br />

Looping over an array, backwards and forwards<br />

The simplest and arguably the fastest way to loop over an array is to use the while<br />

loop.<br />

In the following code, we loop from the beginning of the index to the end.<br />

Sample: sample142.html<br />

<br />

var myArray = ['blue', 'green', 'orange', 'red'];<br />

var myArrayLength = myArray.length; // Cache array length to avoid<br />

unnecessary lookup.<br />

var counter = 0; // Set up counter.<br />

while (counter < myArrayLength) { // Run if counter is less than array<br />

length.<br />

console.log(myArray[counter]); // Logs 'blue', 'green', 'orange',<br />

'red'.<br />

counter++; // Add 1 to the counter.<br />

}<br />

<br />

And now we loop from the end of the index to the beginning.<br />

Sample: sample143.html<br />

<br />

var myArray = ['blue', 'green', 'orange', 'red'];<br />

var myArrayLength = myArray.length;<br />

137

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!