15.02.2013 Views

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

JavaScript Examples Bible - UserWorks Technologies

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.

The Array Object<br />

(Chapter 37)<br />

Whenever you are faced with having to manage any<br />

kind of list or series of related data chunks, the first<br />

technique to turn to is stuffing those chunks into an array.<br />

Once the data is inside an array, your scripts can then perform<br />

quick and easy lookups, based on for loops through<br />

numerically indexed arrays, or via instant searching with the<br />

help of string indexes (à la Java hash tables).<br />

As the examples in this chapter demonstrate, the<br />

<strong>JavaScript</strong> array object features numerous methods to facilitate<br />

managing the data inside an array. It also helps that<br />

<strong>JavaScript</strong> is loose enough to allow arrays to grow or shrink<br />

as their data requires.<br />

Perhaps the two most important features of <strong>JavaScript</strong><br />

arrays to have in your hip pocket are converting arrays to<br />

delimited string objects and sorting. Conversion to strings is<br />

important when you wish to transport data from an array to<br />

another venue that passes only strings, such as passing data<br />

to another page via the URL search string. At the receiving<br />

end, a script converts the search string to an array through<br />

the inverse operation provided by the string.split()<br />

method.<br />

<strong>JavaScript</strong>’s array sorting feature is remarkably powerful and<br />

flexible. Even if the array consists of objects, you can sort the<br />

array based on values assigned to properties of those objects.<br />

<strong>Examples</strong> Highlights<br />

✦ Convert an array into a delimited string via the code<br />

shown in Listing 37-7.<br />

✦ To flip the order of an array without resorting to sorting,<br />

see Example 37-8 for the array.reverse() method.<br />

✦ Listing 37-9 demonstrates a few important aspects of the<br />

array.sort() method. In addition to the traditional<br />

alphabetical sorting, one of the sorting functions operates<br />

on the length property of the string object stored<br />

in each entry of the array. Powerful stuff with very little<br />

code.<br />

17<br />

C H A P T E R<br />

✦ ✦ ✦ ✦<br />

In This Chapter<br />

Converting an array<br />

to a delimited string<br />

Sorting arrays<br />

Combining arrays<br />

and replacing items<br />

in an array<br />

✦ ✦ ✦ ✦

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

Saved successfully!

Ooh no, something went wrong!