An Array object can be created in two ways. First way is by using the new operator as shown below:
var array1 = new Array(10, 20, “hai”);
var array2 = new Array(10);
In the first declaration, the size of array1 is 3 and the values are initialized to 10, 20 and “hai”. In the second declaration, the size of array2 is 10 and the elements are not initialized.
Second way to create an Array object is by specifying an literal array in square brackets as shown below:
var array3 = [1, 2, “hai”];
In the above declaration, size of array3 is 3 and values are initialized to 1, 2 and “hai” respectively.
document.write(“Second array element is: “, array3);
var array1 = new Array(10); //Length is 10
array1.length = 20; //Now length is 20
Several methods are available on an Array object to perform various manipulations on the array elements. Most frequently used methods are mentioned here:
The method join is used to convert the array elements into string and join them into a single string separated by the specified string. If no separator is given, all the elements are joined using commas. Below example demonstrates join method:
var names_array = [“Ken”, “John”, “Mary”];
var names_string = names_array.join(“-“);
Now names_string contains the string “Ken-John-Mary”.
The method reverse is used to reverse the order of array elements and the method sort converts the array elements into strings and then sorts them in alphabetical order.
The method concat appends the specified elements to the end of the Array object as shown below:
var names = [“Ken”, “John”, “Mary”];
var names = names.concat(“Mike”, “James”);
Now, names array contains, “Ken”, “John”, “Mary”, “Mike” and “James”. Length of names array will be 5.
The method slice is used to retrieve subset of elements in an Array object. This method accepts two parameters, starting index and ending index. All the elements from starting index excluding the ending index are retrieved. Below example demonstrates slice method:
var nums1 = [10, 20, 30, 40, 50];
var nums2 = nums1.slice(2,4);
Now nums2 contains [30, 40]. If no ending index is specified, all the elements from starting index to last element in the array are returned.
The method toString is used to convert the array elements into strings and concatenate them using commas. This method behaves same as join method when applied on array of strings.
The methods push and pop behave as stack operations. The method push is used to append an element at the last position in an array and the method pop is used to return the last element of the array.
The methods shift and unshift are used to remove and add elements at the starting index of the array respectively.
var array1 = new Array(1, 2, 3);
var array2 = new Array(2, 3, 4);
var array3 = new Array(1, 3, 4);
var twod = new Array(array1, array2, array3); //Two-dimensional array twod
var twod_array = [ [1, 2, 3], [2, 3, 4], [4, 5, 6] ]; //Two-dimensional array twod_array