the book of javascript 2nd edition phần 4 doc

50 489 0
the book of javascript 2nd edition phần 4 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

KEEPING TRACK OF INFORMATION WITH ARRAYS AND LOOPS The last chapter showed you how JavaScript stores radio buttons and pull-down menu options in lists. In programmer’s parlance, lists are called arrays. This chapter will teach you how to create your own arrays and use them to keep track of large amounts of information. In this chapter, you’ll learn how to: z Use JavaScript’s built-in arrays to control your HTML z Create new arrays of your own information z Use loops to search through arrays for information Real-World Examples of Arrays JavaScript’s built-in arrays are useful in a wide variety of applications. One of the sites I work on, http://www.antweb.org, uses JavaScript’s built-in arrays to show users which species of ants live in various counties in the 124 Chapter 8 San Francisco Bay Area (see Figure 8-1). At the bottom of the list of counties is a Select All checkbox. Clicking this box causes all the other checkboxes to become checked. This trick is easy to script because the checkboxes are stored in an array, allowing me to use JavaScript to check off each one. Browse to http://www.bookofjavascript.com/Websites/AntWeb to see this in action. Figure 8-1: AntWeb checkboxes Creating your own arrays can be useful as well. The Book of JavaScript website employs arrays to show visitors a series of JavaScript programming tips. In the textarea in Figure 8-2, you’ll see one of a dozen programming tips that rotate through this box. I store these tips in a JavaScript array and rotate through the array to put different tips into the textarea. The same principle applies to making a timed slide show, which we’ll see in the next chapter. Figure 8-2: Rotating programming tips on the Book of JavaScript home page JavaScript’s Built-In Arrays When a web browser reads an HTML page, it automatically creates a number of arrays. In the previous chapter we saw that JavaScript creates an array for each set of radio buttons with the same name. If you create a set of radio buttons named age inside a form named the_form, you can refer to the first radio button in the set like this: window.document.the_form.age[0] Keeping Track of Information with Arrays and Loops 125 JavaScript also creates an array for the options in each pull-down menu and scrollable list. Here’s how you could access the second option in a pull- down menu named gender: window.document.the_form.gender.options[1] These are just two of JavaScript’s automatically created arrays. Browsers also automatically create an array of all the image objects on a web page, called images. The same holds true for form elements (the array of form elements is called elements). In Figure 8-3 (part of the Document Object Model), you can see which elements (the boxes with the words array of in them) get automatically created arrays. Figure 8-3: Part of the DOM showing arrays in the document object Each of these arrays is built based on how the page’s creator has written its HTML. In the images array, for example, the first image on a web page is called images[0], the second is images[1], and so on. If you use the images array, you don’t have to name your images to swap them (as in “Swapping Images” on page 58). For example, you can swap the first image on a web page with an image called happy.gif with this line: window.document.images[0].src = 'happy.gif'; THE CURRENT WINDOW self, window, parent, top various Window objects navigator Navigator object frames[] array of Window objects location Location object history History object document Document object Package JavaPackage object elements[] array of HTML Form element objects: Button Checkbox FileUpload Hidden Password Radio Reset Select Submit Text Textarea options[] array of Option objects plugins[] array of Plugin objects mimeTypes[] array of MimeType objects forms[] array of Form objects embeds[] array of JavaObject objects applets[] array of JavaObject objects images[] array of Image objects anchors[] array of Anchor objects mimeType[] array of MimeType objects 126 Chapter 8 Why would you want to use built-in arrays instead of just naming HTML elements? Sometimes you have no choice. As we saw in Chapter 7, because all the radio buttons in a set have the same name, you can access them only using the built-in array. Built-in arrays are also useful when you have many elements on a page. If you have a web page with 100 images, naming them all becomes tedious. Instead, you can just refer to each image by its number (for a set of 100 images, the numbers would be 0 to 99). The best thing about arrays, however, is that a little bit of JavaScript can act on each element in the array—a great time-saving feature if you have a 100-element array. In the AntWeb example, clicking one checkbox (Select All) checks all the individual county checkboxes. It doesn’t matter whether you have a lone checkbox or a thousand of them—the code is the same. To control an entire array as the AntWeb script does, your code needs to determine how many elements the array contains and then go through each element in the array, performing whatever action you want on it. AntWeb, for example, figures out how many checkboxes there are and then checks each one. Figuring Out How Many Items an Array Contains In all modern JavaScript-enabled browsers, an array’s length property contains the number of elements in an array. For example, the script in Figure 8-4 figures out how many images a web page holds. <script type = "text/javascript"> <! hide me from older browsers X var num_images = window.document.images.length; alert("There are " + num_images + " images on this page. "); // show me > </script> Figure 8-4: How many images a web page contains Drop this JavaScript into the bottom of a web page with images, and you’ll see how it works. The critical line is X, which tells JavaScript to create a variable called num_images and set it to the number of images in the built-in images array. If the page has 10 images, num_images will equal 10. Going Through Arrays Once you know how many elements are in an array, you need to write some code that goes through each element. If you have a list of four checkboxes and want to check them all, you could write a script like Figure 8-5. <html> <head> <title>Checking Four Checkboxes</title> Keeping Track of Information with Arrays and Loops 127 <script type = "text/javascript"> <! hide me from older browsers function checkFour() { window.document.the_form.elements[0].checked = true; window.document.the_form.elements[1].checked = true; window.document.the_form.elements[2].checked = true; window.document.the_form.elements[3].checked = true; } // show me > </script> </head> <body> <form name = "the_form"> <input type = "checkbox"> One <br> <input type = "checkbox"> Two <br> <input type = "checkbox"> Three <br> <input type = "checkbox"> Four <br> <input type = "button" value = "check 'em" onClick = "checkFour();"> <br> </form> </body> </html> Figure 8-5: Checking four checkboxes With 1,000 checkboxes the function would end up 1,000 lines long, each line identical to the one before it except for the number between brackets. Writing this would be very tedious. Worse, sometimes, when a page is dynamically generated (see Chapter 13), you don’t know how many checkboxes will appear on a page. In this case, it would be impossible to write a function like the one in Figure 8-5. You can avoid both these problems with a loop. A loop allows you to execute the same JavaScript statements multiple times with slight variations. For example, a loop could execute the following line 1,000 times, changing the number in the brackets each time. window.document.the_form.elements[0].checked = true; The checkFour() function in this script goes through each of the four checkboxes and sets its checked property to true (see the result in Figure 8-6). But this code is not the best solution, since it only works for four checkboxes. To work with five checkboxes, you’d have to add another line to the function. Figure 8-6: The checkboxes checked 128 Chapter 8 while Loops One kind of loop is called a while loop. In plain English, this translates to “While such-and-such is true, do the following.” Figure 8-7 shows a while loop that prints the word happy three times. <html> <head> <title>I'm Happy and I Know It</title> </head> <body> I'm <br> <script type = "text/javascript"> <! hide me from older browsers X var index = 0; Y while (index < 3) Z { [ window.document.writeln("happy<br>"); \ index = index + 1; ] } ^ // show me > </script> and I know it! </body> </html> Figure 8-7: Printing the word happy three times with a while loop Loops are a very common programming technique. They may seem strange the first couple of times you see them, but they are so common that after a while you’ll understand them on sight. The typical while loop starts with a variable set to zero, as in X of Figure 8-7. The variable index is just like any other variable. Once you’ve set this variable, the while loop begins. Line Y reads, “While the variable index is less than three, execute the JavaScript between the curly brackets (Z and ]).” The format of this line is important. The word while must be lowercase, and the Boolean test index < 3 must fall between parentheses. When JavaScript sees Y, it checks whether the variable index has a value less than 3. If so, the script runs the lines between the curly brackets Z and ]. When we start, index is 0, which is less than 3, so the script executes the two lines between Z and ]. Line [ writes the word happy to the web page, and \ adds one to index, changing it from 0 to 1. Once we execute \ and reach the curly bracket in ], JavaScript jumps back to Y to see if index is still less than three. This is the nature of the while loop. Every time JavaScript reaches a loop’s closing curly bracket (]), it jumps back to the beginning of the loop (Y) to see whether the test in the parentheses is still true. Because 1 is less than 3, JavaScript executes [, which prints happy again; it then executes \, adding 1 to index (which now has a value of 2). Keeping Track of Information with Arrays and Loops 129 Again, because we’re in a while loop, JavaScript jumps from ] to Y and checks to see whether index is still less than 3. It is, so [ and \ execute again. The word happy appears a third time, and the script increments index from 2to 3. Once again, JavaScript jumps from ] to Y and checks to see whether index is less than 3. This time, however, index is equal to 3, so the test (index < 3) is not true. The while loop stops and JavaScript jumps to ^, the line after the closing curly bracket. Many people have a hard time with looping, so make sure you understand how it works. You may find it helpful to translate Y into plain English: “While index is less than 3, write happy and add 1 to index.” while Loops and Arrays Now that you know how while loops work, you can apply them to arrays. Look back at the function in Figure 8-5, and notice that each of the four lines is more or less the same: window.document.the_form.elements[some_number].checked = true; The only difference is the number between the square brackets. Now think about the variable index in Figure 8-7. Its value increases by 1 each time the script goes through the loop. This feature makes the index variable ideal for accessing each element in an array. Figure 8-8 uses index to create a more flexible version of Figure 8-5. <html> <head> <title>Checking Four Checkboxes</title> <script type = "text/javascript"> <! hide me from older browsers function checkFour() { X var index = 0; Y while (index < 4) Z { [ window.document.the_form.elements[index].checked = true; \ index = index + 1; ] } ^ } // show me > </script> </head> <body> <form name = "the_form"> <input type = "checkbox"> One <br> <input type = "checkbox"> Two <br> <input type = "checkbox"> Three <br> <input type = "checkbox"> Four <br> <input type = "button" value = "check 'em" onClick = "checkFour();"> <br> 130 Chapter 8 </form> </body> </html> Figure 8-8: Using a loop to check four checkboxes The critical line is [, which says, “Set form element number index to true.” The first time through the loop, index is 0, so [ checks the first form element (the first checkbox). Then \ adds 1 to index, changing index from 0 to 1. JavaScript reaches ] and jumps back to Y, executes [ and \ because index is less than 4, and repeats the process until index equals 4. When index equals 4 and JavaScript jumps to Y, the while loop ends (because index is no longer less than 4) and JavaScript jumps to ^, the line after the closing curly bracket. Combining while loops and arrays is extremely common, so make sure you comprehend the process. The advantage of this kind of code is that it works whether you have just a few checkboxes or a few thousand. To get the code to work for, say, 4,000 checkboxes, you would just change the number in Y from 4 to 4,000. The loop will then run 4,000 times, starting with 0 and finally ending when index equals 4,000. Going Off the Deep End The script in Figure 8-8 looks at the values of form elements 0 through 3, which are the four checkboxes at the start of the form. The next form element in the figure is the button. All input elements have a checked value, although it doesn’t really do anything for a button, so window.document.the_form.elements[4].checked will always be false. But what about this: window.document.the_form.elements[5].checked Here, we’re asking JavaScript to look at the checked value of whatever is stored in the sixth spot in the elements array. Sadly, there’s nothing there; there are only five elements in this form, so JavaScript will respond with the special word undefined. Then, when you ask JavaScript to find the checked value of this undefined thing, it gets confused and you get a JavaScript error. You can prevent this kind of error by making sure that the values stored in the array are defined, like this: if (window.document.the_form.elements[5] != undefined) { var checked_value = window.document.the_form.elements[5].checked; } Notice that there are no quotes around the word undefined. It’s a special word like true and false. Keeping Track of Information with Arrays and Loops 131 Using array.length in Your Loop The code in Figure 8-8 works well, but it could use one improvement. In general, it’s best to have as few literal numbers in your code as possible: Using specific numbers tends to make code apply only in specific situations. In Figure 8-8, for example, Y works only when exactly four checkboxes appear on the page. If you add another checkbox to the web page, you’ll have to remember to change the 4 in Y to 5. Rather than rely on your memory, you should let the computer do the remembering. You can rewrite Y like this: while (index < window.document.the_form.elements.length) The expression window.document.the_form.elements.length always equals the number of form elements on a page, since adding another checkbox automatically increases the length of the elements array. An Incremental Shortcut Lines like \ in Figure 8-8 are used so frequently that programmers have come up with the shorthand index++ to replace index = index + 1. That’s the variable index followed by two plus signs (++), and it saves you the hassle of typing index twice. We’ll be seeing many other shortcuts like this later. Beware of Infinite Loops You should avoid one common loop mistake like the plague. It’s so common that it has a name: the infinite loop. Infinite loops happen when your code enters a loop it can never exit. Figure 8-9 shows you the classic error. var index = 0; while (index < 10) { window.document.write("I am infinite! <br>"); } Figure 8-9: The classic infinite loop—don’t try this at home Running this script will make you sad, so please don’t try it. If you do run it, the script will endlessly write I am infinite! to the page. To stop the script from running, you’d have to quit the browser, which isn’t always easy when you’re stuck in an infinite loop. This loop is infinite because I forgot to add 1 to index after writing “I am infinite!” The index variable starts at 0 and never changes, so index < 10 is always true. Since the test while (index < 10) is always true, the loop continues until you exit the browser. The only way to avoid accidentally writing an infinite loop is to exercise caution. Whenever you write a loop, make sure the loop will exit at some point. [...]... gets the information out of it, fixes the minutes and seconds if necessary, writes the new time into the text box, and sets the time-out again The whole process starts when a visitor clicks the Start the Clock button and ends when the visitor clicks the Stop the Clock button, which cancels the most recently set time-out How the Book of JavaScript Website’s Timer Works The timer on the Book of JavaScript. .. at the name of the checkbox If it is anything other than 'selectAll', the JavaScript will change the checked value of the checkbox I decided to leave that out because the unnecessary effort taken by JavaScript to change the checked value of a checkbox is less than the effort that would be required to examine the name of a checkbox and see whether it is selectAll each time through the script With the. .. this: the_ answers[0] = "yes"; the_ answers[1] = "no"; the_ answers[2] = "maybe"; The first line puts the word yes into the first slot of the array, the next puts no into the second slot, and the third line puts maybe into the third slot You can store values in an array in any order Reversing the three lines above wouldn’t make any difference The word maybe goes into the third slot of the array because the. .. Checking the Last Element in the Array You might be wondering how checks the last element of the array Remember, num_tips equals the number of items in the array If the array has three items, num_tips equals three However, because the first element in the array is zero, the last element in an array will be two the length of the array minus one To look at the last element of an array, use the following... How the Book of JavaScript Tip Box Works The Book of JavaScript website has a little textarea that shows various programming tips The script keeps these tips in an array and then uses JavaScript to loop through the array, showing one tip at a time Each tip stays in the textarea for 3.5 seconds before the next one appears I should confess that I got the idea for this tip box from something that the. .. reached the end of the array Remember, set num_tips to the length of the array, so num_tips - 1 is the position of the array’s last element If index is greater than num_tips - 1, we’ve reached the array’s end, and executes It sets the variable index back to 0, so the next time the script puts tips[index] into the textarea, index will indicate the first question in the array Finally, determines how fast the. .. Limits of Arrays You may have noticed that before checks to see whether the last element in the array is a blank string, it makes sure there is at least one tip in the array If there are no elements in the array, num_tips will equal 0 If that’s the case, then the second part of the while loop would be checking to see whether tips[0 – 1] == "", or doing the math, tips[-1] Because arrays start at 0, there... Analysis of Figure 8-12 Line in Figure 8-12 creates the array and sets up the loop, saying, “While index is less than the number of items in the array, execute the JavaScript between the curly brackets.” The first time through the loop, index is 0, so when looks up rainbow_colors[index], it gets the first item in the array, the value red Line assigns this value to window.document.bgColor, which sets the. .. line in the function’s body, stores the number of elements in the form into a variable named count There are four elements in this form the three county checkboxes and the Select All checkbox—so count will be 4 Line stores the checked value of the selectall checkbox: either true, if the checkbox was just checked, or false, if it was unchecked The real fun begins with the loop, starting in The first... o ps 141 By the time the script reaches , the visitor has filled the array’s first four positions Line initializes a variable that stores the contents of the Mad Lib The next few lines, starting with , build this string Each line adds content to the string Line adds “Once upon a time there was a user answer.” The next line appends “who was very user answer” to the end of the string Line writes the complete . elements (the boxes with the words array of in them) get automatically created arrays. Figure 8-3: Part of the DOM showing arrays in the document object Each of these arrays is built based on how the. colors to the array in X. 136 Chapter 8 How the Book of JavaScript Tip Box Works The Book of JavaScript website has a little textarea that shows various pro- gramming tips. The script keeps these. looks at the name of the checkbox. If it is anything other than 'selectAll', the JavaScript will change the checked value of the checkbox. I decided to leave that out because the unnecessary

Ngày đăng: 06/08/2014, 09:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan