JavaScript_Succinctly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Using brackets to access the index in the array, then the property<br />
blue.<br />
console.log(myArray[50]['color']); // Logs 'blue'.<br />
// Using dot notation.<br />
console.log(myArray[50].color); // Logs 'blue'.<br />
<br />
Length vs. index<br />
An array starts indexing values at zero. This means that the first numeric slot to hold a<br />
value in an array looks like myArray[0]. This can be a bit confusing—if I create an<br />
array with a single value, the index of the value is 0 while the length of the array is 1.<br />
Make sure you understand that the length of an array represents the number of values<br />
contained within the array, while the numeric index of the array starts at zero.<br />
In the following sample, the string value blue is contained in the myArray array at the<br />
numeric index 0, but since the array contains one value, the length of the array is 1.<br />
Sample: sample138.html<br />
<br />
var myArray = ['blue'] // The index 0 contains the string value 'blue'.<br />
console.log(myArray[0]); // Logs 'blue'.<br />
console.log(myArray.length); // Logs 1.<br />
<br />
Defining arrays with a predefined length<br />
As I mentioned earlier, by passing a single integer parameter to the Array()<br />
constructor, it’s possible to predefine the array’s length, or the number of values it will<br />
contain. In this case, the constructor makes an exception and assumes you want to set<br />
the length of the array and not pre-populate the array with values.<br />
In the next sample, we set up the myArray array with a predefined length of 3. Again,<br />
we are configuring the length of the array, not passing it a value to be stored at the 0<br />
index.<br />
Sample: sample139.html<br />
<br />
var myArray = new Array(3);<br />
135