Array Power, Part I - DHTML Lab | 9
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().
How we actually drag the element, or reposition it, are not topics to be discussed here. (You can, of course, always view the source of this page.) We have attempted to demonstrate the use of an array to store information as a stack would, using unshift() and shift(). Storing information in and retrieving from a stack is vital to any application, and certainly to Web Applications using DHTML.
In a follow-up article, we will prototype the remainder of the Array methods which Explorer lacks, and create a use-everywhere external JS file for convenience.
Until then, Happy Stacking!
Produced by Peter Belesis and
All Rights Reserved. Legal Notices.Created: April 26, 2000
Revised: April 26, 2000
URL: https://www.webreference.com/dhtml/column31/5.html