Using the Java Script Array Object
array.sort
The sort method is often used by writing your own sorting function and then
passing a reference to the sort method. If you use the sort method with
no reference parameter, it converts the array elements to strings and performs a
string sort, modifying the original array. The code below creates an array of names,
and then uses the sort method with no parameter to sort the array.
var employee = new Array("Jim Shoe","Bob Sled","Dugg Graves");
employee.sort();
document.write(employee);
Output:
Bob Sled,Dugg Graves,Jim Shoe
If you attempt to use the sort method on an array containing numeric values,
it will convert the array elements to strings and perform a string sort, producing
incorrect results.
array.toString
The toString method converts an array to a string. The code below creates an
array named employee, initializing it with three fictitious employee names. If you
were to assign the array to a variable, you would be creating a reference to the
original array. If you use the toString method before assigning the array to a
variable, you would be creating a new String object. The code shown below creates
a String object containing the string "Jim Shoe,Bob Sled,Dugg Graves".
var employee = new Array("Jim Shoe","Bob Sled","Dugg Graves");
var strNames = employee.toString();
Note that I didn't use the alert or document.write method to display the
value in strNames. That's because whenever you call one of those methods to display
the contents of an array, it automatically uses the toString method. You would only
need the toString method if you were going to do some processing on the array
contents as a string.
Using an Array as a Stack
Those of us who used to program microprocessors in assembly language are familiar with
the concept of a stack. When the program executed an interrupt, the values of the
microprocessor's registers would be "pushed" onto the "stack". After the interrupt
was handled, the values would be "popped" off the "stack" and returned to the registers
to resume normal execution.
With Java Script, an array can be used as a stack. The code shown below creates
an array named stack and initializes it with four string elements. The code then
"pops" an element from the end of the array and "unshifts" (puts) it to the beginning of
the array. It then "shifts" (removes) it from the beginning of the array and "pushes" it
back on the end of the array, restoring the array to its original contents.
|