JavaScript Arrays

This is a post about JavaScript. I get these questions all the time and thought I’d start adding a few JavaScript tips on my site.

Arrays are a special kind of object in JavaScript. To create one just do the following:

// standard arrays
var arr = new Array();
arr[0] = "value";

// multiple items in constructor
var arr2 = new Array("test","test2");

// associative arrays
var arr3 = new Array();
arr3["key"] = "val";

Here’s a list of methods you might want to use:

  • length – to get the length/size of an array
  • pop – removes last element from an array
  • push – adds another element to the end of an array
  • join – joins allĀ elementsĀ of an array into a string
  • slice – extracts a section of an array and returns a new array
Some examples of the methods above:
var arr = new Array("aaa","bbb","ccc");
// length property
alert(arr.length); // returns 3
// pop
alert(arr.pop); // returns "ccc"
// push
alert(arr.push("ddd"); // adds "ddd" to array

Multi-Dimensional Arrays look like this:

var mArr = new Array();
mArr[0] = new Array();
mArr[0][0] = "test";