Arrays

Arrays are containers that can hold primitive and reference values. Arrays are ordered, that is, when a value is inserted into an array it is added at a specific position in the array.  The value will remain at that position until it is explicitly moved.  A value stored in an array is referred to as an element of the array and the position of an element in an array is referred to as the index of the element in the array.

Indices are non-negative numbers (0, 1, 2, …).  If an array has n elements in the array, valid indices for the elements in the array are {0, 1, 2, …, n-1}.

Initializing and Accessing Arrays

Arrays can be created using the Array constructor or an array literal.

var addr1 = new Array();
var addr2 = new Array(4);     // length is set to 4
var addr3 = new Array('123 Main St', 'Dallas', 'TX', 12345);   // mixing types is ok
var addr4 = Array(4);         // omitting the new keyword is ok

var addr6 = [];               // creates an empty array
var addr5 = ['123 Main St', 'Dallas', 'TX', 12345];   

Elements can be added and retrieved at a specific index using brackets []. In the example below the array is initialized with one element (‘yellow’) in it.  The second statement overwrites the element at index 0 with the string ‘blue’.  The third and fourth lines add two more elements to the array. The last statement retrieves the element at index 0 and prints it to the console.

var colors = ['yellow'];
colors[0] = 'blue';
color[1] = 'green';
color[2] = 'red';
console.log(colors[0]);   // prints 'blue'

The Length Property

We can get the length of an array using the length property.

console.log(colors.length);   // prints 3

You can truncate the array by setting the length property.

colors.length = 2;      // truncates the array
console.log(colors.length);   // prints 2

The length property can be used as the index to add an element to the end of the array.

colors[colors.length] = 'yellow';   // element added to index 2
console.log(colors.length);         // prints 3

Elements can also be added at indices beyond the length of the array.  In this case, elements of type Undefined are added at the indices containing no elements.

colors[4] = 'orange'; 
console.log(colors[3]);  // prints 'undefined'

Named Indices

Just like objects, arrays are sets of key/value pairs.  We’ve seen earlier that we can change the value and get the value of an element at a particular index using brackets and an integer index.  Similarly, when we add elements to an array via a push(), unshift(), and splice() the elements are added at locations with integer indices.

We can also use text labels as indices in arrays.  For example, we can store the value ‘George’ with an index of name.  These named indices do not change the value of the array’s length property.  They are also not included in the string returned by toString() and are not iterated over in a for-of loop.  They are, however, iterated over in a for-in loop.

var list = [10,20,30]; 
console.log("length: " + list.length);    // 3 
list[name] = 'George'; 
console.log("length: " + list.length);    // 3 
list[list.length] = 'red'; 
console.log("length: " + list.length);    // 4 

console.log(list.toString());             // prints '10,20,30,red' - does not include 'George'

Looping Through Arrays

For-of loops can be used to loop through all of the values of an array that have integer indices.  Named indices are not included.

for (var value of list) {
    console.log(value);    // prints 10,20,30,'red' - does not include 'George'
}

For-in loops can be used to loop through the indices of an array, including named indices.  Named indices however can not be printed.

for (var index in list) {
    console.log(index);        // prints '0','1','2','3'," " - the named index is not printed, but is usable
}

for (var index in list) {
    console.log(list[index]);  // prints 10,20,30,'red','George' - notice the order
}

Detecting Arrays

To determine if an object is an Array we can use the static isArray() method of the Array class.

if (Array.isArray(colors)) {
    // do something
}

Converting Arrays to Strings

All objects have the following methods:toString() and valueOf(). Both return the same value for arrays: a comma separated string that contains the string equivalents of each element in the array.

console.log(colors.toString());  // prints 'blue,green,yellow,,orange'

The array’s join() method takes a character as an argument and returns a string containing the string representation of the elements in the array separated by the character in the parameter.

var colors = ['red','blue','green'];
var str = colors.join('|');             // “red|blue|green”

© 2018 – 2021, Eric. All rights reserved.