Declare
Declare and Populate
Populate
Length
Add Items
Remove Items
Replace Items
Sorting
Other Methods
Declare
Create a new array with n null items:
var myArray = new Array(n)
Create a new empty array with no items:
var myArray = new Array()
Declare and Populate
Declare a new array and populate it at the same time:
var myArray = new Array(anyVar1, anyVar2, anyVar3, anyVar4, anyVar5)
Or:
myArray = [anyVar1, anyVar2, anyVar3, anyVar4, anyVar5]
Populate
Set the value of the item at position n:
myArray[n] = anyVar
Set the value of the item called myItem:
myArray.myItem = anyVar
Length
The length property of the array is the number of items in the array, which is one greater than the index value of the last item in the array:
myArray.length
Add Items
Add a new item to the end of an array, increasing the length by one:
myArray[myArray.length] = anyVar
Or:
myArray.push(anyVar)
Add a new item to the front, increasing the length by one and increasing the index value of all other items by one:
myArray.unshift(anyVar)
Insert items into the middle of an array, starting at position s and inserting items x, y, and z (as many or as few as you like) (N4+ and IE5.5+):
myArray2 = myArray1.splice(s, 0, x, y, z)
Remove Items
Deleting an item removes the item at position n so that it is no longer accessible, but does not reduce the array's length:
delete myArray[n]
Remove the last item, reducing the length by one:
myArray.pop()
Remove the first item, reducing the length by one and decreasing the index value of all other items by one:
myArray.shift()
Delete a section from of the middle of an array, starting at position s and deleting n items (the second parameter is optional, if omitted all remaining items are deleted) (N4+ and IE5.5+):
myArray2 = myArray1.splice(s, d)
Replace Items
Replace items in the middle of an array, starting at position s and deleting d items, replacing them with items x, y, and z (as many or as few as you like, the number of inserted items doesn't have to match the number of deleted items) (N4+ and IE5.5+):
myArray2 = myArray1.splice(s, d, x, y, z)
Sorting
Sort the order of items. Calls a user-defined function, which shoud return a number less than zero to swap any two items, greater then zero to leave them as they are, or zero to indicate they are the same. The function can be as complicated as you like:
function mySortFunction(a,b) { return a - b } myArray.sort("mySortFunction")
Reverse the order of items:
myArray.reverse()
Other Methods
Concatenate two arrays:
myArray1.concat(myArray2)
Return a delimited string listing all values in an array (the example uses a comma delimiter):
stringArray = myArray.join(",")
Return a section from of the middle of an array, starting at position s and finishing one item before postion f (the second parameter is optional, if omitted the returned array goes all the way to the end):
myArray2 = myArray1.slice(s, f)