Using the Array Object


Using the Array Object

You can create a new array in a variety of ways using the Array constructor:

 var array1 = new Array()                //Creates an empty array  var array1 = new Array([size])  var array1 = new Array([element0 [, element1[, ... [, elementN]]]]) 

Here are the arguments I'm using in this code:

  • size . The size of the new array.

  • element0 to elementN . The elements to put into the array, initializing it. This creates an array with N + 1 elements.

We've seen how to work with arrays in Chapter 2, but I'm going to take a look at working with Array objects in more detail now.

Initializing Arrays

You can initialize an array by providing a list of elements that you want in the array, like this:

 var array1 = new Array([element0 [, element1[, ... [, elementN]]]]) 

This initializes element 0 through element N of the array. In fact, as of NS4+ and IE4+, you can just use the [] array constructor, which is just a pair of square brackets, like this:

 var array1 = [element0, element1, ... elementN] 

As mentioned in Chapter 2, you also can use names to refer to elements in an array, like this:

 array1["name"] = "Ralph" 

In fact, you can even use this syntax:

 array1.name = "Ralph" 

Or this syntax to store "Ralph" as element 4 in an array:

 array1.4 = "Ralph" 

Tip

What if you try to create a new array with the expression new Array(1) ? Up to NS3 and IE4, that expression created an array of length 1, where the single element was undefined . Now it creates an array of length 1, where the single element is set to 1.


Sorting Arrays

You can use the sort method to sort arrays. Here's an example, where I'm sorting an array containing the names "Ralph" , "Ed" , "Alice" , and "Trixie" :

(Listing 19-06.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Sorting Arrays          </TITLE>      </HEAD>      <BODY>          <H1>Sorting Arrays</H1>          <FORM NAME="form1">              <TEXTAREA NAME="textarea1" ROWS="4"></TEXTAREA>          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--             var array1 = new Array("Ralph", "Ed", "Alice", "Trixie")  array1.sort()  for(var loopIndex = 0; loopIndex < array1.length; loopIndex++){                  document.form1.textarea1.value += array1[loopIndex] + "\n"              }              // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the results in Figure 19.6, where the elements "Ralph" , "Ed" , "Alice" , and "Trixie" have been sorted in ascending text order.

Figure 19.6. Sorting an array.

graphics/19fig06.gif

You also can define the sort order yourself if you supply a custom sorting function. If you use a sorting function, it must return one of the following values:

  • A negative value if the first value passed to the function is less than the second value in the sorting order you want.

  • A positive value if the first value passed to the function is greater than the second value.

  • Zero if the two values are equal.

Using the values you return from this sorting function, JavaScript can sort the elements in the array in the order you want.

Instead of sorting the elements in an array in ascending text order, for example, I could sort them in reverse order by supplying a sorting function, which I'll call reverser :

 array1.sort(reverser) 

Here's the reverser function, which reverses the normal sort order:

 function reverser(a, b)  {      if(a < b) return 1      if(a > b) return -1      return 0  } 

You can see the results in Figure 19.7, where you see the array sorted in reverse order. Using sort functions like this, you can create all kinds of sorts on all kinds of data items, including objects.

Figure 19.7. Sorting an array in reverse order.

graphics/19fig07.gif

Here's the code for this example:

(Listing 19-07.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Sorting Arrays          </TITLE>      </HEAD>      <BODY>          <H1>Sorting Arrays</H1>          <FORM NAME="form1">              <TEXTAREA NAME="textarea1" ROWS="4"></TEXTAREA>          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--             var array1 = new Array("Ralph", "Ed", "Alice", "Trixie")  array1.sort(reverser)  for(var loopIndex = 0; loopIndex < array1.length; loopIndex++){                  document.form1.textarea1.value += array1[loopIndex] + "\n"              }  function reverser(a, b)   {   if(a < b) return 1   if(a > b) return -1   return 0   }  // -->          </SCRIPT>      </BODY>  </HTML> 

Multidimensional Arrays

Inherently, JavaScript Array objects are one-dimensionalthat is, all the elements in the array are indexed with one index value alone. However, you can create multidimensional arrays by creating an array of arrays .

What does that mean? Let's see an example. Suppose that I want to create an array that's 4-by-3 (that is, four rows and three columns ). Each row can store a first name, a last name, and an ID number. We can create such an array by making each element in that array an array itself. Here's how you can do that, where we're creating an array of arrays:

 var array1 = [new Array("Ralph",  "Kramden", 1),      new Array("Ed",     "Norton",  2),      new Array("Alice",  "Kramden", 3),      new Array("Trixie", "Norton",  4)] 

If you're using a recent browser (NS4+ and IE4+), you can use the [] array constructor like this:

 var array1 = [["Ralph",  "Kramden", 1],      ["Ed",     "Norton",  2],      ["Alice",  "Kramden", 3],      ["Trixie", "Norton",  4]] 

That makes it clear how we're setting up and initializing this two-dimensional arrayas four rows of three columns each. Each row is itself a subarray of the main array.

So how do you address an element in a multidimensional array like this? You can use the syntax array[ row ][ column ] ; where row is the row, and column is the column of the element you're addressing. If we want to load the first and last names from the array array1 we just created into a <SELECT> control, select1 , for example, the code to do so might look like this:

 document.form1.select1.options[0].text = array1[0][0] +      " " + array1[0][1]  document.form1.select1.options[1].text = array1[1][0] +      " " + array1[1][1]  document.form1.select1.options[2].text = array1[2][0] +      " " + array1[2][1]  document.form1.select1.options[3].text = array1[3][0] +      " " + array1[3][1] 

Here's an example that uses this code and loads the first and last names from our array into a <SELECT> control; when the user clicks one of the items in the <SELECT> control, we can display that person's ID value in a text field like this:

(Listing 19-08.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Creating Multi-dimensional Arrays          </TITLE>      </HEAD>      <BODY>          <H1>Creating Multi-dimensional Arrays</H1>          <FORM NAME="form1">  <SELECT NAME="select1" ONCHANGE="reportID(this.selectedIndex)">   <OPTION NAME="option1">   <OPTION NAME="option2">   <OPTION NAME="option3">   <OPTION NAME="option4">   </SELECT>  <BR>              <INPUT TYPE="TEXT" NAME="text1">          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--  var array1 = [["Ralph",  "Kramden", 1],   ["Ed",     "Norton",  2],   ["Alice",  "Kramden", 3],   ["Trixie", "Norton",  4]]   document.form1.select1.options[0].text = array1[0][0] +   " " + array1[0][1]   document.form1.select1.options[1].text = array1[1][0] +   " " + array1[1][1]   document.form1.select1.options[2].text = array1[2][0] +   " " + array1[2][1]   document.form1.select1.options[3].text = array1[3][0] +   " " + array1[3][1]   function reportID(id)   {   document.form1.text1.value = "That person's ID is " + (id + 1)   }  // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the results in Figure 19.8.

Figure 19.8. Creating multidimensional arrays.

graphics/19fig08.gif

Pushing and Popping

Another popular programming operation when handling arrays is to push and pop elements. Pushing an element appends it to the end of the array, and popping it removes it from the end of the array.

Here's an example. In this case, I'll just push six numbers , 0 to 5, onto an array with the push method:

 document.form1.text1.value = "Pushing "  for(var loopIndex = 0; loopIndex <= 5; loopIndex++){      document.form1.text1.value += loopIndex + ", "      array1.push(loopIndex)  } 

Next I'll pop them off the array with pop . Note that they'll come off the array in reverse order, because you push elements onto the end of the array and also pop them from the end of the array:

 document.form1.text2.value = "Popping "  for(var loopIndex = 0; loopIndex <= 5; loopIndex++){      document.form1.text2.value += array1.pop() + ", "  } 

Tip

Pushing and popping like this enables you to simulate programming constructions called stacks . Want to work with the start of the array rather than the end? Use shift and unshift , not push and pop . See Table 19.10.


Here's the full code for this example, which pushes elements onto an array and displays the pushed elements, and then pops them and displays them in the order they come off the array. All operations are displayed in text fields:

(Listing 19-09.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Pushing and Popping          </TITLE>      </HEAD>      <BODY>          <H1>Pushing and Popping</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1">              <BR>              <INPUT TYPE="TEXT" NAME="text2">          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--             var array1 = new Array()              document.form1.text1.value = "Pushing "              for(var loopIndex = 0; loopIndex <= 5; loopIndex++){                  document.form1.text1.value += loopIndex + ", "                  array1.push(loopIndex)              }              document.form1.text2.value = "Popping "              for(var loopIndex = 0; loopIndex <= 5; loopIndex++){                  document.form1.text2.value += array1.pop() + ", "              }              // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the results in Figure 19.9.

Figure 19.9. Pushing and popping elements in an array.

graphics/19fig09.gif

That's it for our work with the Math , Number , Boolean , and Array objects in this chapter. As you can see, there's plenty of programming support in these utility objects. In the next chapter, we're going to work with something we've already come across in the preceding chapter: regular expressions, which enable you to search through and handle text expressions.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net