JavaScript_Succinctly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
It is more common to see an array defined using the literal syntax, but it should be<br />
noted that this shortcut is merely concealing the use of the Array() constructor.<br />
Notes<br />
In practice, the array literal is typically all you will ever need.<br />
Regardless of how an array is defined, if you do not provide any predefined values to<br />
the array, it will still be created but will simply contain no values.<br />
Adding and updating values in arrays<br />
A value can be added to an array at any index, at any time. In the sample that follows,<br />
we add a value to the numeric index 50 of an empty array. What about all the indexes<br />
before 50? Well, like I said, you can add a value to an array at any index, at any time.<br />
But if you add a value to the numeric index 50 of an empty array, <strong>JavaScript</strong> will fill in all<br />
of the necessary indexes before it with undefined values.<br />
Sample: sample136.html<br />
<br />
var myArray = [];<br />
myArray[50] = 'blue';<br />
console.log(myArray.length); /* Logs 51 (0 is counted) because JS created<br />
values 0 to 50 before "blue".*/<br />
<br />
Additionally, considering the dynamic nature of <strong>JavaScript</strong> and the fact that <strong>JavaScript</strong><br />
is not strongly typed, an array value can be updated at any time and the value<br />
contained in the index can be any legal value. In the following sample, I change the<br />
value at the numeric index 50 to an object.<br />
Sample: sample137.html<br />
<br />
var myArray = [];<br />
myArray[50] = 'blue';<br />
myArray[50] = { 'color': 'blue' }; // Change object type from string to<br />
Object() object.<br />
console.log(myArray[50]); // Logs 'Object {color="blue"}'.<br />
134