Array
var arr = new Array(1,2,3,4,5); alert(arr.toString()); //1,2,3,4,5 arr.push(13); //add 13 to the end of array alert(arr.toString()); //1,2,3,4,5,13 arr.push(20,30,40); //add 20, 30, 40 to the end of array alert(arr.toString()); //1,2,3,4,5,13,20,30,40
If you want to add an element to the array start position, use
var arr = new Array(1,2,3,4,5); alert(arr.toString()); //1,2,3,4,5 arr.unshift(13); //add 13 to the start position of array alert(arr.toString()); //13,1,2,3,4,5
If you want to add elements to the specified position, you can use
var arr = [4,2,8,5,3,3,100,500]; var arr2 = arr.splice(3,0,11,12); //arr2 is [4,2,8,11,12,5,3,3,100,500]
The
var arr = new Array(1,2,3,4,5); var ret = arr.pop(); alert(arr); //1,2,3,4 alert(ret); //5
You may also define an insert method which can add an element to a specific position.
Array.prototype.insert = function (i,elem) { this.splice(i,0,elem); } var arr = [4,2,8,5,3,3,100,500]; arr.insert(3,11); //arr is [4,2,8,11,5,3,3,100,500]