Javascript Arrays, Explanation and Examples
Javascript, it’s been around for a long time, but we always seem to come back and use them in our code. Because a lot of us code in multiple languages, we tend (or I tend) to get mixed up sometimes. So, here’s a quick reference.
We typically use javascript arrays because we want to loop through some data for posting, whether it’s for a drop down box, or error checking.
Here’s one way to create a simple javascript array.
var myArray=new Array(); //Here, we are creating an empty array called myArray
Here’s how to add some values to that array, remember they are 0 based:
var myArray=new Array();
myArray[0]=”part”;
myArray[1]=”time”;
myArray[2]=”webmaster”;
What if we want to put this all on one line?
var myArray=new Array(“part”,”time”,”webmaster”);
How do we access a particular array item? Using the text below, you will get the first item.
myArray[0];
How many items are in an array?
myArray.length;
How to loop through an array. Note, the x will be used as our index.
for (x in myArray)
{
document.write(myArray[x] + “<br />”);
}
How do we merge 2 javascript arrays? Note, you can use a count of the number of values in an array as shown below.
var myArray1 = new Array(3);
myArray1[0] = “part”;
myArray1[1] = “time”;
myArray1[2] = “webmaster”;
var myArray2= new Array(3);
myArray2[0] = “javascript”;
myArray2[1] = “array”;
myArray2[2] = “example”;
document.write(myArray1.concat(myArray2));
How do we easily write all of the elements in the array?
document.write(myArray.join() + “<br />”);
If you have any other examples, feel free to post them here. Happy coding!
