11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

stack.pop(); // ["first", 10] Returns 20<br />

stack.push(2); // ["first", 10, 2]<br />

stack.pop(); // ["first", 10] Returns 2<br />

stack.pop(); // ["first"] Returns 10<br />

stack.pop(); // [] Returns "first"<br />

Of course, you can use push() and pop() to add data to and remove data from the end of an<br />

array without thinking of it as an actual stack.<br />

<strong>JavaScript</strong> also provides unshift() and shift() methods. <strong>The</strong>se methods work as push() and<br />

pop() do, except that they add and remove data from the front of the array. Invoking unshift()<br />

inserts its arguments (in order) at the beginning of the array, shifts existing elements to higher<br />

indices, and increments the array‘s length property accordingly. For example,<br />

var myArray = [345, 78, 2];<br />

myArray.unshift(4,"fun");<br />

alert(myArray);<br />

adds two more elements to the front of the array, as shown here:<br />

Calling shift() removes the first element from the array, returns it, shifts the remaining elements<br />

down one index, and decrements length. You can think of shift() as shifting each element in<br />

the array down one index, causing the first element to be ejected and returned; so, given the<br />

previous example, if we called<br />

myArray.shift();<br />

we would end up with an array containing ―fun,‖ 345, 78, and 2. As with pop(), invoking shift()<br />

on an array returns a value that can be used. For example, we could save the value shifted off<br />

the array into a variable:<br />

var x = myArray.shift();<br />

You can use push() and shift() to simulate a queue. <strong>The</strong> following example illustrates the<br />

principle. We place new data at the end of the array and retrieve data by removing the element<br />

at index zero. <strong>The</strong> contents of the array and any return values are indicated in the comments.<br />

var queue = [];<br />

queue.push("first", 10); // ["first", 10]<br />

queue.shift(); // [10] Returns "first"

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

Saved successfully!

Ooh no, something went wrong!