Array Power, Part I - DHTML Lab | 9 | WebReference

Array Power, Part I - DHTML Lab | 9

Logo

Array Power, Part I
creating a stack


There are, of course, countless uses for shift() and unshift(), especially if used in combination.

I think the most obvious is for manipulating an array that acts as a stack. A programming stack is, simply, a repository of information that works with the last-in, first-out concept.

That is, the last bit of information to be added to the stack is the first to be retrieved.

Browser History

As a browser user you have been exposed to the stack concept every time you click your browser's Back button. Your browser's history is a stack. If all the URLs you visit are unshifted into an array, then you can use shift() to retrieve them, not in the order you visited them, but most-recent first.

Undo

This last-in, first-out behavior is also the basis for Undo features in editors. The action to be undone is always the last one executed. Successive selection of an undo option takes us back through our editing history.

Demo

Below, you'll find a draggable red square. Move it around the page. (Don't forget that in Navigator, the square will not render above form elements. See DHTML Diner.)

Release your mouse; then drag again. Every time you grab the square, its position is stored in an array using unshift(). The contents of the array are displayed one-element-per-line in the textarea for reference. Every element is a two-element array, containing the left and top pixel position of the square on the page when it was grabbed.

When you click the Undo button, the square is moved to its previous position. In otherwords, the drag event is undone. This is accomplished by retrieving the first element of the array using shift().