Did you find this useful?
Socialize it today.


JavaScript Array Object

Tuesday, April 24, 2012

In JavaScript, an array object can be used to store more than one value in a single variable. Creating an array is slightly different from creating a normal variable. There are a few methods used to create JavaScript arrays. In this first example, an array is created using the new constructor, then each of the members of the Array are assigned variables through an index.


var myColors=new Array(); 
myColors[0]="Red";
myColors[1]="White";
myColors[2]="Blue";


In this example, the array is constructed and the values are assigned in one statement.


var myColors=new Array("Red","White","Blue");


You can create an Array with a specific number of members, without having to assign the values. While this is not recommended, the following example creates an Array with 10 empty members.


var myColors=new Array(10);


In JavaScript the use of the new constructor is not required when creating arrays, as shown in this example.

var myColors=["Red","White","Blue"];


You do not need to specifiy how many members the Array will contain. JavaScript will automatically increase the size of the Array as needed.


var myColors=[];


Creating an Array with brackets instead of with the new constructor avoids confusion where you want to initialize only one integer.


var myColors=[10];


How to Use Arrays

Once you assign values to an Array, you can access the members of the array and modify the values as well. Keep in mind that the first index in an Array is [0], so if you want to access the third member of the Array, you can do so as follows:


document.write(myColors[2]);


If you want to modify the value of the first member of the Array you would do so as follows:


myColors[0]="Yellow";


Array Object Length Property

All Array objects have a length property. This property contains the number of elements in the array. The length property is convenient for loops. You can use a loop and counter to easily compare against the number of members or even navigate through its members by looping through the index.


for (var x=0; x<myArray.length; x++)

for (x = 0; x <= 10; x++) {
myArray[x]="Some Value";
}


Array Object Methods

Just as other JavaScript objects, Arrays have methods you can use. Here is a listing of the Array object methods


MethodDescription
concat()Joins multiple arrays
indexOf()Search the array for an element and returns its position
join()Joins all elements of an array into a string
lastIndexOf()Returns the last item in the array which matches the search critera
pop()Removes the last element of an array
push()Adds new elements to the end of an array
reverse()Reverses the order of the elements in an array
shift()Removes the first element of an array
slice()Selects a part of an array, and returns the new array
sort()Sorts the elements of an array
splice()Adds/Removes elements from an array
toString()Returns the array as a string
unshift()Adds new elements to the beginning of an array
valueOf()Returns the primitive value of an array


concat()

The concat() method is used to join multiple arrays. This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.


var myArrayA = [1,2,3];
var myArrayB = [4,5,6];
var myArrayC = [7,8,9];
var joined = myArray.concat(myArrayB,myArrayC);
document.write(joined);


indexOf()

The indexOf method will search the array until it matches your search criteria. It will then return the index where the item was found.


var myArray = ["red","white","blue"];
document.write(myArray.indexOf("blue"));


join()

The join method will output your Array as a string with a delimiter of your choice.


var myArray = [1,2,3,4,5,6];
var joined = myArray.join('* ');
document.write(joined+'');


lastIndexOf()

The lastIndexOf is similar to indexOf, except it searches from last to first.


var myArray = ["red","white","blue"];
document.write(myArray.lastIndexOf("blue"));


pop()

The pop method removes the last element of an array. This method changes the length of an array.


var myArray = ["red","white","blue"];
var myPop = myArray.pop();
document.write(myArray);


push()

The push method adds new items to the end of an array. The new item(s) will be added at the end of the array. This method changes the length of the array.


var myArray = ["red","white","blue"];
myArray.push("yellow");
document.write(myArray);


reverse()

The reverse method reverses the order of the members of the array.


var myArray = ["red","white","blue"];
myArray.reverse();
document.write(myArray);


shift()

The shift method removes the first item of an array. This method changes the length of an array.


var myArray = ["red","white","blue"];
myArray.shift();
document.write(myArray);


slice()

The slice method returns the selected members in an array, as a new array object. The slice method requires that you specify the start and end index. However, the end index is not included in the new array. The original array will not be changed. Keep in mind that the array index begins at zero.


var myArray = ["red","white","blue","yellow"];
var newArray = myArray.slice(1,3);
document.write(newArray);


sort()

The sort method sorts the items of an array. The sort order can be either alphabetic or numeric, and either ascending or descending. The default sort order is alphabetic and ascending. You can create a function and pass the sort order as a parameter in the method as well.


var myArray = [1,5,9,4,2,3];

myArray.sort();
document.write(myArray);

document.write("<br />")

myArray.sort(sortMe);
document.write(myArray);

function sortMe(x,y){
return y - x;
}


splice()

The splice method adds or removes items to and from an array. This method changes the original array.  In the following example, we first use the splice method with no additional items to be added.  We are simply telling JavaScript to move to index[2] and remove two items.  The next splice method moves to index[1], removes zero items, then adds to additional strings to the array.


var myArray = ["red","white","blue","yellow"];
myArray.splice(2,2);
myArray.splice(1,0,"black","green");
document.write(myArray);


toString()

The toString method converts an array into a String and returns the result. The returned string will separate the elements in the array with commas.


var myArray = [1,2,3,4,5,6,7,8,9];
myArray.toString();
document.write(myArray);


unshift()

The unshift method adds new items to the beginning of an array. This method changes the length of an array.


var myArray = [1,2,3,4,5,6,7,8,9];
myArray.unshift("+",0);
document.write(myArray);


valueOf()

The valueOf method returns the primitive value of an array.


var myArray = [1,2,3,4,5,6,7,8,9];
var newArray = myArray.valueOf();
document.write(newArray);


Always keep in mind that JavaScript is case sensitive.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

HTML CSS and JavaScript Editor Professional JavaScript for Web Developers JavaScript and jQuery: The Missing Manual