17.11.2015 Views

JavaScript_Succinctly

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 15 Array()<br />

Conceptual overview of using Array() objects<br />

An array is an ordered list of values typically created with the intention of looping<br />

through numerically indexed values, beginning with the index zero. What you need to<br />

know is that arrays are numerically ordered sets, as opposed to objects which have<br />

property names associated with values in non-numeric order. Essentially, arrays use<br />

numbers as a lookup key, while objects have user-defined property names. <strong>JavaScript</strong><br />

does not have true associative arrays, but objects can be used to achieve the<br />

functionality of associative arrays.<br />

In the following sample, I store four strings in myArray that I can access using a<br />

numeric index. I compare and contrast myArray to an object literal mimicking an<br />

associative array.<br />

Sample: sample133.html<br />

<br />

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

console.log(myArray[0]); // Logs blue using the 0 index to access the<br />

string in myArray.<br />

// Versus<br />

var myObject = { // aka an associative array/hash, known as an object in<br />

<strong>JavaScript</strong>.<br />

'blue': 'blue',<br />

'green': 'green',<br />

'orange': 'orange',<br />

'red': 'red'<br />

};<br />

console.log(myObject['blue']); // Logs blue.<br />

<br />

Notes<br />

Arrays can hold any type of values, and these values can be updated or deleted at any<br />

time.<br />

If you need a hash (aka associative array), an object is the closest solution.<br />

131

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

Saved successfully!

Ooh no, something went wrong!