Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Looping Through Object Properties

A third type of loop is available in JavaScript. The for…in loop is not as flexible as an ordinary for or while loop. Instead, it is specifically designed to perform an operation on each property of an object.

For example, the navigator object contains properties that describe the user's browser, as you'll learn in Hour 15, "Unobtrusive Scripting." You can use for…in to display this object's properties:

for (i in navigator) {
    document.write("property: " + i);
    document.write(" value: " + navigator[i] + "<br>");
}

Like an ordinary for loop, this type of loop uses an index variable (i in the example). For each iteration of the loop, the variable is set to the next property of the object. This makes it easy when you need to check or modify each of an object's properties.

Try It Yourself

Working with Arrays and Loops

To apply your knowledge of loops, you will now create a script that deals with arrays using loops. As you progress through this script, try to imagine how difficult it would be without JavaScript's looping features.

This simple script will prompt the user for a series of names. After all of the names have been entered, it will display the list of names in a numbered list. To begin the script, initialize some variables:

names = new Array();
i = 0;

The names array will store the names the user enters. You don't know how many names will be entered, so you don't need to specify a dimension for the array. The i variable will be used as a counter in the loops.

Next, use the prompt statement to prompt the user for a series of names. Use a loop to repeat the prompt for each name. You want the user to enter at least one name, so a do loop is ideal:

do {
    next = prompt("Enter the Next Name", "");
    if (next > " ") names[i] = next;
    i = i + 1;
   }
    while (next > " ");

Did you Know?

If you're interested in making your scripts as short as possible, remember that you could use the increment (++) operator to combine the i = i + 1 statement with the previous statement: names[i++]=1.


This loop prompts for a string called next. If a name was entered and isn't blank, it's stored as the next entry in the names array. The i counter is then incremented. The loop repeats until the user doesn't enter a name or clicks Cancel in the prompt dialog.

Next, your script can display the number of names that was entered:

document.write("<h2>" + (names.length) + " names entered.</h2>");

This statement displays the length property of the names array, surrounded by level 2 heading tags for emphasis.

Next, the script should display all the names in the order they were entered. Because the names are in an array, the for…in loop is a good choice:

document.write("<ol>");
for (i in names) {
    document.write("<li>" + names[i] + "<br>");
}
document.write("</ol>");

Here you have a for…in loop that loops through the names array, assigning the counter i to each index in turn. The script then prints the name with a <li> tag as an item in an ordered list. Before and after the loop, the script prints beginning and ending <ol> tags.

You now have everything you need for a working script. Listing 7.4 shows the HTML file for this example, and Listing 7.5 shows the JavaScript file.

Listing 7.4. A Script to Prompt for Names and Display Them (HTML)

<html>
<head>
<title>Loops Example</title>
</head>
<body>
<h1>Loop Example</h1>
<p>Enter a series of names. I will then
display them in a nifty numbered list.</p>
<script language="JavaScript" type="text/javascript"
src="loops.js">
</script>
</body>
</html>

Listing 7.5. A Script to Prompt for Names and Display Them (JavaScript)

// create the array
names = new Array();
i = 0;
// loop and prompt for names
do {
    next = window.prompt("Enter the Next Name", "");
    if (next > " ") names[i] = next;
    i = i + 1;
    } while (next > " ");
document.write("<h2>" + (names.length) + " names entered.</h2>");
// display all of the names
document.write("<ol>");
for (i in names) {
    document.write("<li>" + names[i] + "<br>");
}
document.write("</ol>");

To try this example, save the JavaScript file as loops.js and then load the HTML document into a browser. You'll be prompted for one name at a time. Enter several names, and then click Cancel to indicate that you're finished. Figure 7.3 shows what the final results should look like in a browser.

Figure 7.3. The output of the names example, as shown by Firefox.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Hour 5. Using Variables, Strings, and Arrays
Hour 6. Using Functions and Objects
Hour 7. Controlling Flow with Conditions and Loops
The if Statement
Using Shorthand Conditional Expressions
Testing Multiple Conditions with if and else
Using Multiple Conditions with switch
Using for Loops
Using while Loops
Using do…while Loops
Working with Loops
Looping Through Object Properties
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 8. Using Built-in Functions and Libraries
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele