Arrays
- Array elements are zero-based.
- Arrays are objects.
- Trailing commas at the end of array
literals are ignored.
- An array literal is a type of object
initializer.
Indexed array
var numArray = new Array(1);
numArray[0] = new Array(2);
numArray[0][0] = "red";
numArray[0][1] = "round";
# Array literal
var colors = ["orange", "blue", "green"];
var animals = ["lion", , "zebra"]; # animals[1] is undefined.
var fish = ["bass", , ,]; # This array contains only 1 element.
Associative array
var assocArray = new Array();
assocArray["apple"] = new Array();
assocArray["apple"]["color"] = "red";
assocArray["apple"]["shape"] = "round";
# Array literal (JavaScript Object Notation (JSON))
var assocArray = {"lemon":"yellow", "lime":"green"};
Properties
length
- The number of elements in the
array.
Methods
concat
- Joins two arrays and returns a
new array.
var myArray = arr1.concat(arr2);
join
- Joins all elements of an array
into a string.
var myStr = myArray.join(", ");
pop
- Removes and returns the last
element from an array.
push
- Adds one or more elements to the
end of an array and
returns the last element added.
reverse
- Reverses the order of the array
elements.
shift
- Removes and returns the first
element from an array.
slice
- Returns a portion of an array and
as a new array.
splice
- Adds and/or removes elements
from an array.
sort
- Sorts the array elements.
unshift
- Adds one or more elements to
the front of an array
and returns the new length of the array.