Reading and Writing Array Elements


Elements of an array are accessed using square brackets, sometimes termed the [] operator. (In JavaScript, the [] operator can also be used to access object properties, as I show you in Chapter 7, “ Working with Objects.”)

This means that it’s easy to save a value to an array element or to retrieve a value from an array element.

Here are some examples of reading and writing array elements:

 var theVal = theArray[5];  // retrieves the value of the sixth element of theArray and  // stores the value in the variable theVal  theArray[0] = 256.17;  // stores the floating point numeric value 256.17 in the first  // element of theArray  var i = 1;  theArray[i] = "Good morning";  // stores the text string "Good morning" to theArray[1]  theArray[i +1] = 12  // stores the integral numeric value 12 to theArray[2] 

Let’s look at an example that’s a bit more complete. The code shown in Listing 6-1 declares a four-element array, assigns a value to each element of the array, and then retrieves an element and displays it as part of a text string (see Figure 6-1).

Listing 6.1: Reading and Writing Array Elements

start example
 <HTML> <HEAD> <TITLE>     Year of the ?     </TITLE> </HEAD> <BODY> <H1> <SCRIPT>        var myArray = new Array(4);        myArray[0] = "dog";        myArray[1] = "cat";        myArray[2] = "snake";        myArray[3] = "dragon";        var i = 3;        var theYear = myArray[i];        document.write("It is the year of the " + theYear + ".");     </SCRIPT> </H1> </BODY> </HTML> 
end example

click to expand
Figure 6-1: The text value in the array element is displayed.

In part, the example shown in Listing 6-1 demonstrates that a variable can be used for the index of an array. The ability to do this is part of what gives arrays their power, as you’ll see in the examples later in this chapter.

Try This at ome

As you can see from this example (Listing 6-1), it’s really easy to assign values to array elements and to retrieve values from arrays. Because this is so easy to do, you should try it—so you can make sure you’re comfortable with arrays!




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

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