Arrays
- Indexed arrays 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.
("one,two,three").split(",") // Equivalent to ["one", "two", "three"]
Associative array
// Array literal (JSON syntax)
var assocArray = {lemon:"yellow", lime:"green"};
var a = 1, b = 2, myArray = {a:a, b:b}; // Equivalent to {a:1, b:2}
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 alphabetically.
- To sort numeric elements, a helper function must be provided:
function sortNumber(a, b) { return a - b; } // Ascending order
[3,1,4,2].sort( sortNumber ) // [1, 2, 3, 4]
[3,1,4,2].sort( function(a, b){return a - b;} ) // [1, 2, 3, 4]
unshift
- Adds one or more elements to the front of an array and returns the new length of the array.
Resources URL:
notes/javascript/resources
Sources URL:
notes/javascript/sources