Array Use
Severak types of arrays can be used in JScript. The following information explains how to use some of these arrays and how to choose an appropriate array for your particular application.
One-Dimensional Arrays
The following example shows how to access the first and last elements of the addressBook array. This assumes that another part of the script defines and assigns a value to addressBook. Since arrays are zero-indexed in JScript, the first element of an array is zero and the last element is the length of the array minus one.
var firstAddress = addressBook[0];
var lastAddress = addressBook[addressBook.length-1];
Arrays of Arrays vs. Multidimensional Arrays
You can store data that is referenced by several indices in either arrays of arrays or multidimensional arrays. Each type of array has unique features.
Arrays of arrays are useful for applications in which each subarray has a different length. The subarrays can easily be reorganized, which helps with sorting of array elements. An example of a typical use is a calendar, where a Year array stores twelve Month arrays, and each Month array stores data for the appropriate number of days.
Multidimensional arrays are useful for applications in which the size of the array in each dimension is known at the time of declaration. Multidimensional arrays are more efficient than arrays of arrays in terms of speed and memory consumption. Multidimensional arrays must be typed arrays. An example of a typical use is a matrix used for mathematical calculations, where the array size is fixed and known from the start.
Looping over JScript Array Elements
Since JScript arrays are sparse, an array may have a large numbers of undefined elements between the first element and the last element. This means that if you use a for loop to access the array elements, you must check if each element is undefined.
Fortunately, JScript provides a for...in loop that allows you to easily access only the defined elements of a JScript array. The following example defines a sparse JScript array and displays its elements using both the for loop and the for...in loop.
var a : Array = new Array;
a[5] = "first element";
a[100] = "middle element";
a[100000] = "last element";
print("Using a for loop. This is very inefficient.")
for(var i = 0; i<a.length; i++)
if(a[i]!=undefined)
print("a[" + i + "] = " + a[i]);
print("Using a for...in loop. This is much more efficient.");
for(var i in a)
print("a[" + i + "] = " + a[i]);
The output of this program is:
Using a for loop. This is very inefficient.
a[5] = first element
a[100] = middle element
a[100000] = last element
Using a for...in loop. This is much more efficient.
a[5] = first element
a[100] = middle element
a[100000] = last element
See Also
Reference
Concepts
Multidimensional Arrays (Visual Studio - JScript)