Array Power, Part II - DHTML Lab | 6
Array Power, Part II
pop()
The pop() method
removes the last element from an array and returns that element..
Once again, let's use myArray from the previous examples:
myArray = [0,"cat",true];, or
myArray = new Array(0,"cat",true);
We want to remove the last element from myArray, truncating myArray, and assign it to a variable we'll call finalGuy.
Without pop()
We can remove the last element with these statements:
Statement used | myArray becomes | |
1. | finalGuy = myArray[myArray.length-1]; | |
2. | myArray.length = Math.max(myArray.length-1,0); | [0,"cat"] |
First we assign the value of the last element to finalGuy. Then we remove it by decrementing the length property of the array. We make sure that the minimum length of myArray is 0, as we did with shift().
With pop()
The last element can be removed, and assigned, with a single statement:
finalGuy = myArray.pop();
myArray would then look like as expected:
["cat",true]
pop() is probably the most straightforward method of all the new array methods we've discussed. All Navigator JavaScript interpreters treat it the same and prototyping it for use with Explorer is easy.
Produced by Peter Belesis and
All Rights Reserved. Legal Notices.Created: May 2, 2000
Revised: May 2, 2000
URL: https://www.webreference.com/dhtml/column32/6.html