But you should have a general sense of how array methods work, so we’ll quickly look at the reverse, sort, and concat methods. Rough equivalents to these three Array object methods are available in any modern programming language.
To start with, let’s declare and populate a small (four-element) array to use as an example:
var theArray = new Array("Neo","Morpheus","Trinity","Mr. Smith");
To Reverse the Array:
Call the reverse method of the Array object, for example, with this statement:
The array is now reversed as shown in the second line of text in Figure 6-12. Note that the actual elements of the array have been rearranged in reverse order (this is different from returning a copy of the array with its elements reversed).
Figure 6-12: Reversing, sorting, and concatenating an array
To Sort the Array:
Call the sort method of the Array object, for example, with this statement:
The array has now been sorted using a default sort method as shown in the third text line in Figure 6-12. Like the reverse method, the sort method changes the order of the elements in place, this time by sorting them alphabetically (converting numbers to strings as needed).
To Concatenate Elements onto an Array:
Call the concat method of the Array object with the elements you want to concatenate onto the array. For example, to concatenate two new elements onto theArray, use the following:
The fourth line of text in Figure 6-12 shows the Cypher and Mouse elements concatenated to the existing elements of theArray.
If you open the code shown in Listing 6-10 in your Web browser, you’ll see an original array, then the array reversed, sorted, and with the two concatenated elements.
Listing 6.10: Reversing, Sorting, and Concatenating an Array
<HTML> <HEAD> <TITLE> Array methods </TITLE> <HEAD> <BODY> <H1> <SCRIPT> var theArray = new Array("Neo","Morpheus","Trinity","Mr. Smith"); document.write ("Original array: " + theArray); document.write ("<br>"); theArray.reverse(); document.write ("Reversed array: " + theArray); document.write ("<br>"); theArray.sort(); document.write ("Sorted array: " + theArray); document.write ("<br>"); document.write("Concatenated: " + theArray.concat("Cypher", "Mouse")); </SCRIPT> </H1> </BODY> </HTML>