Wednesday, February 22, 2012

JavaScript Array Cheatsheet

var a = []; // An empty array
var b = [1, 2, 3];

b.length // Note: length is NOT a method
// 3

// Appends elements to an array, and returns the new length
a.push(4); 
// 1
// a = [4]
a.push(5, 6);
// 3
// a = [4, 5, 6]

// Merge two arrays. 
// This method will NOT affect the original arrays
b.concat(a);
// [1, 2, 3, 4, 5, 6]
// a = [4, 5, 6]
// b = [1, 2, 3]
var c = b.concat(a, [7], [8, 9, 10]);
// a = [4, 5, 6]
// b = [1, 2, 3]
// c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

// Removes the last element, and returns that element
c.pop(); 
// 10
// c = [1, 2, 3, 4, 5, 6, 7, 8, 9]

// Removes the first element, and returns that element
c.shift(); 
// 1
// b = [2, 3, 4, 5, 6, 7, 8, 9]

// Add elements to the beginning of the array, 
// and returns the new length
c.unshift(1); 
// 9
// c = [1, 2, 3, 4, 5, 6, 7, 8, 9]
c.unshift(-1, 0);
// 11
// c = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// Array can have mixed types of elements
c = [1, 2, '3', 'a', 'b', true]; 

The versatile splice method adds and/or deletes elements to/from an array, and returns the deleted elements.

array.splice( index, count, element1, ..., elementN )

var c = [1, 2, '3', 'a', 'b', true]; 

// Deletes 1 element starting at the element of index 2 (0-based), 
// and returns the deleted elements
c.splice(2, 1); 
// ['3']
// c = [1, 2, 'a', 'b', true]

// Deletes 2 elements starting at the element of index 1 (0-based), 
// and returns the deleted elements
c.splice(1, 2); 
// [2, 'a']
// c = [1, 'b', true]

// Deletes 1 elements starting at the element of index 1 (0-based), 
// Inserts 'A' and 'B', 
// and returns the deleted elements
c.splice(1, 1, 'A', 'B')
// ['b']
// c = [1, 'A', 'B', true]

// Inserts 'X' at index 1
c.splice(1, 0, 'X');
// [] Didn't delete anything
// c = [1, 'X', 'A', 'B', true]