Using the Array Class to Create ArraysArrays are programming constructs that can hold a set of data items that you access item by item with a numeric index. Arrays are perfect for programming because, using the array index, you can reach each item in the array. So, you can easily iterate over every item in the array using a loop. To create arrays, you use the JavaScript Array class. You can find the methods of this class in Table 6-5 and the methods of the JScript Array class in Table 6-6. Table 6-5. Methods of the JavaScript Array Class
Table 6-6. Methods of the JScript Array Class
Let's see an example to make this concrete. In this case, I'll create an array that will hold the student scores from an exam. I'll use a for loop to add them all, finding the average score by dividing the total sum by the number of elements in the array. I start by creating a new array named scores to hold the student scores, and a variable named runningSum to hold the sum of all the scores: var scores = new Array() var runningSum = 0 . . . You can refer to the first item in the scores array as scores[0] , the next as scores[1] , and so on. So, I can store the students' scores in the scores array like this (you can also pass those values to the Array class's constructor): var scores = new Array() var runningSum = 0 scores[0] = 43 scores[1] = 87 scores[2] = 92 scores[3] = 70 scores[4] = 55 scores[5] = 61 . . . Now I can add the scores in a for loop this way: var scores = new Array() var runningSum = 0 scores[0] = 43 scores[1] = 87 scores[2] = 92 scores[3] = 70 scores[4] = 55 scores[5] = 61 for(var loopIndex = 0; loopIndex < scores.length; loopIndex++){ runningSum += scores[loopIndex] } . . . All that's left is to divide the total of all the scores by the number of elements in the array; you can find the length of an array with its length property, this way: var scores = new Array() var runningSum = 0 cores[0] = 43 cores[1] = 87 cores[2] = 92 cores[3] = 70 cores[4] = 55 cores[5] = 61 for(var loopIndex = 0; loopIndex < scores.length; loopIndex++){ runningSum += scores[loopIndex] } document.write("The average student score is " + runningSum / scores.length) Here's the final code in a Web page: Listing ch06_13.html<HTML> <HEAD> <TITLE> Using Arrays in JavaScript </TITLE> </HEAD> <BODY> <CENTER> <H1> Using Arrays in JavaScript </H1> </CENTER> <SCRIPT LANGUAGE = "JavaScript"> var scores = new Array() var runningSum = 0 scores[0] = 43 scores[1] = 87 scores[2] = 92 scores[3] = 70 scores[4] = 55 scores[5] = 61 for(var loopIndex = 0; loopIndex < scores.length; loopIndex++){ runningSum += scores[loopIndex] } document.write("The average student score is " + runningSum / scores.length) </SCRIPT> </BODY> </HTML> You can see the results of this JavaScript in Figure 6-13, where you see that the average score is 68 . Figure 6-13. Using arrays in JavaScript.
|