|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Using Numeric ArraysAn array is a numbered group of data items that you can treat as a single unit. For example, you might use an array called scores to store several scores for a game. Arrays can contain strings, numbers, objects, or other types of data. Each item in an array is called an element of the array. Creating a Numeric ArrayUnlike most other types of JavaScript variables, you typically need to declare an array before you use it. The following example creates an array with four elements: scores = new Array(4); To assign a value to the array, you use an index in brackets. Indexes begin with 0, so the elements of the array in this example would be numbered 0 to 3. These statements assign values to the four elements of the array: scores[0] = 39; scores[1] = 40; scores[2] = 100; scores[3] = 49; You can also declare an array and specify values for elements at the same time. This statement creates the same scores array in a single line: scores = new Array(39,40,100,49); In JavaScript 1.2 and later, you can also use a shorthand syntax to declare an array and specify its contents. The following statement is an alternative way to create the scores array: scores = [39,40,100,49]; Did you Know? Remember to use parentheses when declaring an array with the new keyword, as in a=new Array(3,4,5), and use brackets when declaring an array without new, as in a=[3,4,5]. Otherwise, you'll run into JavaScript errors. Understanding Array LengthLike strings, arrays have a length property. This tells you the number of elements in the array. If you specified the length when creating the array, this value becomes the length property's value. For example, these statements would print the number 30: scores = new Array(30); document.write(scores.length); You can declare an array without a specific length, and change the length later by assigning values to elements or changing the length property. For example, these statements create a new array and assign values to two of its elements: test = new Array(); test[0]=21; test[5]=22; In this example, because the largest index number assigned so far is 5, the array has a length property of 6remember, elements are numbered starting at 0. Accessing Array ElementsYou can read the contents of an array using the same notation you used when assigning values. For example, the following statements would display the values of the first three elements of the scores array: scoredisp = "Scores: " + scores[0] + "," + scores[1] + "," + scores[2]; document.write(scoredisp); Did you Know? Looking at this example, you might imagine it would be inconvenient to display all the elements of a large array. This is an ideal job for loops, which enable you to perform the same statements several times with different values. You'll learn all about loops in Hour 7. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |