Array initialization, you can use the
var arr = new Array(1,2,3,4,5); var arr = new Array(); var arr = []; var arr = [1,2,3,4,5];
javascript array is indexed from 0 to
var arr = new Array(1,2,3,4,5); var x = arr[2]; // x = 3
var arr = new Array(1,2,3,4,5); var x = arr.length; // x = 5
var arr = new Array(1,2,3,4,5); arr.push(13); //add 13 to the end of array
var arr = new Array(1,2,3,4,5); arr.pop(); //delete 5
var arr = new Array(1,2,3,4,5); arr.shift(); //delete 1, arr now is [2,3,4,5]
var arr = new Array(1,2,3,4,5); arr.unshift(10); //arr now is [10,1,2,3,4,5]
var arr = new Array(1,2,3,2,5); var p = arr.indexOf(3) //p = 2 p = arr.indexOf(7) //p = -1 p = arr.indexOf(2) //p = 1
var arr = new Array(1,2,3,2,5,11,14); var p = arr.lastIndexOf(3) //p = 2 p = arr.lastIndexOf(7) //p = -1 p = arr.lastIndexOf(2) //p = 3
var arr = new Array(1,2,3,2,5,11,14); arr.reverse(); //arr now is [14,11,5,2,3,21]
var arr = new Array(1,2,3,2,5,11,14); arr.sort(); //arr now is [1,2,2,3,5,11,14]
var arr = new Array("e","n","d","memo"); var s = arr.join(); //s is "perschon"
var arr1 = [4,2,8]; var arr2 = new Array(5,3,3); var arr3 = [100,500]; var newarr = arr1.concat(arr2,arr3); //newarr is [4,2,8,5,3,3,100,500]
var arr = [4,2,8,5,3,3,100,500]; var newarr = arr.slice(2,5); //newarr is [8,5,3] var newarr = arr.slice(2); //newarr is [8,5,3,3,100,500]
var arr = [4,2,8,5,3,3,100,500]; var arr2 = arr.splice(2,4); //arr2 is [4,2,100,500] var arr3 = arr.splice(3,0,11,12); //arr3 is [4,2,8,11,12,5,3,3,100,500]
var arr = [4,2,8,5,3,3,100,500]; var s = arr.toString(); //s="4,2,8,5,3,3,100,500"
var arr = [4,2,8]; var x = arr.valueOf(); //x = "4 2 8"
Loop through an array:
var arr = [2,4,5,8,1,3,9]; for (var i=0; i<arr.length; i++) { if (arr[i] % 2 == 0) alert(arr[i]); //2,4,8 } for (var i in arr) { if (arr[i] % 2 == 0) alert(arr[i]); //2,4,8 }
var arr = [4,2,8]; var x = arr.constructor; //x = "function Array() {[native code]}"
Array.prototype.sqrt = function() { for (var i=0; i<this.length;i++) { this[i] = Math.sqrt(this[i]); } } var arr = [4,16,9]; arr.sqrt(); //arr now is [2,4,3]