18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Object Basics<br />

which returns only the last item, “yellow”, and stores it in the variable vItem. The array is then left<br />

with only the strings “red” and “green”.<br />

The push() method is actually the same as manually adding the array items as shown in previous<br />

examples. This example could be rewritten as the following:<br />

var stack = new Array;<br />

stack[0] = “red”;<br />

stack[1] = “green”;<br />

stack[2] = “yellow”;<br />

alert(stack.toString());<br />

var vItem = stack.pop();<br />

alert(vItem);<br />

alert(stack.toString());<br />

//outputs “red,green,yellow”<br />

//outputs “yellow”<br />

//outputs “red,green”<br />

The Array also provides methods to manipulate the very first item. The shift() method removes the first<br />

item in the array and returns it as the function value. On the other end of the spectrum, the unshift()<br />

method places an item into the first position of the array, shifting all other items down one position in the<br />

process. Example:<br />

var aColors = [“red”, “green”, “yellow”];<br />

var vItem = aColors.shift();<br />

alert(aColors.toString()); //outputs “green,yellow”<br />

alert(vItem);<br />

//outputs “red”<br />

aColors.unshift(“black”);<br />

alert(aColors.toString()); //outputs “black,green,yellow”<br />

In this example, the string “red” is removed (shift()ed) from the array, leaving only “green” and<br />

“yellow”. By using the unshift() method, the string “black” is placed at the front of the array, effectively<br />

replacing “red” as the new value in the first position.<br />

By using shift() and push(), it is possible to make an Array object behave like a queue. A queue is a<br />

member of the group of data structures that restricts the insertion and removal of elements. A queue is<br />

referred to as a last-in-last-out (LILO) structure, meaning that the most recently added element is the last<br />

one removed. The insertion of elements always occurs only at the back of the queue whereas the<br />

removal of elements occurs only at the front of the queue.<br />

When you think of a queue, think of a line at the movies. When new people arrive to get tickets, they go<br />

to the back of the line (Figure 3-3). This is traditionally called put or enqueue.<br />

Start<br />

1 2 3 4<br />

Put<br />

1 2 3 4<br />

5<br />

Result<br />

Figure 3-3<br />

1 2 3 4 5<br />

75

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!