Array Power, Part II - DHTML Lab | 6
Array Power, Part II
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.
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().
The last element can be removed, and assigned, with a single statement:
finalGuy = myArray.pop();
myArray would then look like as expected:
Produced by Peter Belesis andAll Rights Reserved. Legal Notices.
Created: May 2, 2000
Revised: May 2, 2000