JS push & pop


Array push() method adds element to the array end. It returns the array length.

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 unshift() method.

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 splice(i,0,...) method. It add elements to the array, and return new array. "i" - array position, "..." - elements to be added.

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 pop() method deletes the last element of an array, and returns the deleted value.

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]



endmemo.com © 2024  | Terms of Use | Privacy | Home