Changes

JavaScript Arrays

1,301 bytes added, 14:17, 15 May 2007
How to Create a JavaScript Array
== How to Create a JavaScript Array ==
 
A new instance of a JavaScript array object is created in the same way as any other object in JavaScript suing the ''new'' keyword. For example we can create a new array object instance called ''myColors'' as follows:
 
<pre>
var myColors = new Array();
</pre>
 
We can also specifiy the intial size of the array when we create it by passing through the number of elements that we require the array to hold as an argument to the Array() object constructor. For example, to intialize an array to hold 7 items:
 
<pre>
var myColors = new Array(7);
</pre>
 
'''Note:''' An array will grow automatically as new items are added so it is not necessary to specifiy at creation time the number of elements you believe the array will need. The decision as to whether to pre-allocate the initial size of the array is typically one of memory and speed. a mission critical application that needs to store a large amount of data in an array may not want the dealy associated with waiting for the size of the array to be increased each time an item is added. In this situation the array would be pre-initialized by specifying an initial size. This then has the trade off that a large amount of memory may be taken up an d not used right away. In practice it is usually acceptable to let array grow as items are added.