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

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

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

Setting length to a value greater than the index of the last valid element has no effect on the<br />

array contents, though it will increase the number of undefined slots in the array. Consider, for<br />

example, the result of the following script,<br />

var myArray = ["red", "green", "blue"];<br />

myArray.length = 20;<br />

alert("myArray="<br />

which is shown here:<br />

You shouldn‘t bother setting the length property directly, since the result of extending an array<br />

is usually a sparsely populated array. However, deletion through this method is acceptable. For<br />

example, removing the last element in the array with this capability is a bit unwieldy:<br />

myArray.length = myArray.length - 1;<br />

Newer versions of <strong>JavaScript</strong> provide a better way to remove the last element with methods the<br />

Array object provides to simulate stacks and queues.<br />

Arrays as Stacks and Queues<br />

<strong>JavaScript</strong> 1.2+ and JScript 5.5+ provide methods for treating arrays like stacks and queues.<br />

For those readers unfamiliar with these abstract data types, a stack is used to store data in lastin<br />

first-out order, often called LIFO. That is, the first object placed in the stack is the last one<br />

retrieved when the stack is read. A queue is an abstract data type used to store data in first-in<br />

first-out order, also called FIFO. Data in a queue is retrieved in the order it was added.<br />

A stack in the form of an array is manipulated using the push() and pop() methods. Calling<br />

push() appends the given arguments (in order) to the end of the array and increments the<br />

length property accordingly. Calling pop() removes the last element from the array, returns it,<br />

and decrements the length property by one. An example of using the properties is as follows.<br />

<strong>The</strong> contents of the array and any values returned are indicated in the comments.<br />

var stack = []; // []<br />

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

stack.push(10, 20); // ["first", 10, 20]

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

Saved successfully!

Ooh no, something went wrong!