1. Trang chủ >
  2. Giáo án - Bài giảng >
  3. Tin học >

Chapter 6. Controlling Flow with Conditionals and Loops

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.5 MB, 505 trang )


120



Part II  Applying JavaScript

if (some condition) {

// do something here

}



Note  The if statement is sometimes called the if conditional. I use these terms interchangeably

within this and other chapters to get you comfortable with both terms. But don’t confuse the if

conditional (the entire if statement) with the if condition, which is the Boolean expression that

the if statement evaluates.



The if statement examines the validity, or truthfulness, of a condition to determine whether

the code within the conditional (inside the braces) is to be executed. The condition is a

Boolean expression that, when evaluated to true, causes the if statement to execute the code

in the conditional. (You can negate an expression in the condition to cause the code to run

if the expression evaluates to false.) Recall the use of Boolean and unary operators from

Chapter 5, “Using Operators and Expressions.” Here’s an example:

if (! some condition) {

// do something here

}



In this case, the condition starts with the negation operator, which means that the condition

would need to evaluate to false for the code inside the conditional to execute.

The real-world airline cost example from earlier in the chapter might look like this in

pseudocode:

if (flightCost < 350) {

bookFlight();

}



If the flight costs less than $350, the code within the conditional executes. The garbage

example might look like this:

if (forecast != "windy") {

takeGarbageOut();

}



Later in this chapter, I show you how to use an else statement to cause other code to execute

when the condition is true.

You use if statement with many of the operators you learned about in Chapter 5, especially

relational operators that test whether one value is greater than or less than another value

and equality operators that test whether two values are equal to each other. Take a look at

these examples:







Chapter 6  Controlling Flow with Conditionals and Loops



121



var x = 4;

var y = 3;

// Equality test

if (x == y) {

// do something

}



Because the value in the variable x (4), does not equal the value in variable y (3), the code

within the if conditional (inside the braces) doesn’t execute. Here’s an example with a relational operator:

var x = 4;

var y = 3;

// Relational test

if (x > y) {

// do something

}



In this case, because the value in variable x (4) is greater than the value in variable y (3), the

code within the braces executes.

The next section shows an example that you can perform yourself. This example takes advantage of the prompt() function to get input from a visitor through a simple interface.



The prompt() Function in Internet Explorer

With the introduction of Windows Internet Explorer 7, the prompt() function is no longer

enabled by default. If you attempt to use the prompt() function with Internet Explorer, you

receive a security warning like the one shown in Figure 6-1, or possibly a page with the word

null, like the warning in Figure 6-2.



Figure 6-1  A security warning caused by the prompt() function in Internet Explorer.



Figure 6-2  When using the javascript: pseudo-protocol with the prompt() function, you can sometimes

receive a page with the word null.



122



Part II  Applying JavaScript



You can reliably get around this feature by clicking the information bar (shown in Figure 6-1)

and selecting an option to allow scripts, or by changing the security settings. You can change

security settings in Internet Explorer, for example, by selecting Internet Options from the

Tools menu, clicking the Security tab, clicking Custom Level, and enabling the Allow Web

Sites To Prompt For Information Using Scripted Windows option within the Scripting section.

However, you can’t rely on your visitors doing the same with their Internet Explorer settings.

Therefore, the prompt() function is no longer as useful as it was before Internet Explorer 7

was introduced. Some programmers might argue that the prompt() function was annoying

(and I agree that it created problems sometimes), but it did have its advantages, and disabling

it does very little to enhance security. But sometime it’s useful for test purposes, such as in

the following exercise.



Using if to make decisions about program flow





1. Using Microsoft Visual Studio, Eclipse, or another editor, edit the ifexample.htm file in

the Chapter06 sample files folder, which you can find in the companion content.







2. In the page, replace the TO DO comment with the following code shown in boldface

type, (this code is also in the ifexample.txt file in the companion content):


"http://www.w3.org/TR/html4/strict.dtd">





An If Example







This is an example from Chapter 6.













3. Save the page and view it in a web browser. If you attempt to view the page in Internet

Explorer and receive a security warning, you need to change your security settings as

described previously. You can also use Firefox or another browser instead.







Chapter 6  Controlling Flow with Conditionals and Loops



123







4. When you view the page, you see a prompt asking for a number below 100. Internet

Explorer typically fills in the text box with undefined in the dialog box. Type a number

and click OK. I typed , as you can see here:







5. Click OK. You see a page like the one here:







6. Reload the page in the browser, and this time, when prompted, type a number greater

than 100. You receive an alert like this one:



Aside from the Hypertext Markup Language (HTML) and opening script tags, which you’ve

seen in previous examples, the code works as follows:



124



Part II  Applying JavaScript



The first line within the body’s

This is an example from Chapter 6.









The statement in Listing 6-1 uses the logical OR operator and reads, “If inputNum is greater

than 99 or inputNum is less than 51, do this.”

Consider again the example we’ve been using for much of this chapter. If you enter a number

greater than 99 or less than 51, you receive an alert. But what if the input is not a number at

all? What if you entered the word boo? You wouldn’t receive the alert because the condition

being used checks only whether the variable is above or below specified numbers.

Therefore, the code should check whether the value contained in the variable is a number.

You can accomplish this task with the help of the isNaN() function and by nesting the decision, like this:

if (isNaN(inputNum) || ((inputNum > 99) || (inputNum < 51))) {

alert("That number, " + inputNum + ", is not between 50 and 100.");

}



The conditional is now evaluated to first check whether the value in the inputNum variable is

a number. If this initial check proves true (the user did not enter a number), no further processing is done, preventing the rest of the statement from being evaluated. If the user did

enter a number, the isNaN check fails, and the if statement performs the checks for the range

of numbers, which are nested together between parentheses, creating their own conditional

set. The result, when run with the input value of boo, is shown in Figure 6-3.



Figure 6-3  Running the example with the isNaN() function in a nested conditional.



126



Part II  Applying JavaScript



The full code is shown in Listing 6-2 (in the listing6-2.htm file in the companion content). The

nested condition is shown in boldface.

Listing 6-2  A nested if statement.


"http://www.w3.org/TR/html4/strict.dtd">





An If Example






>





This is an example.









Using else if and else Statements

The next problem with the code example used so far is that the alert dialog box text in Figure

6-3 always indicates that a number was entered. That obviously isn’t always the case—I entered

the word boo. What you really need is a way to perform multiple separate conditional checks.

How can you do this? Here’s where else if and else become useful.



Else if

Most modern programming languages have the if/else if/else conditional constructs,

but they differ in how they use those constructs, especially the way they spell or construct the else if statement. Some languages define it as elsif, all one word (and misspelled). Others define it as elseif—all one word but spelled correctly. Remembering

these different constructs is a challenge, and this discussion hasn’t even considered

the different ways that languages use braces to define the code to be executed. In

JavaScript programming, you use else if—two words, both spelled correctly.







Chapter 6  Controlling Flow with Conditionals and Loops



127



Using else if and else, you can create multiple levels of conditions, each of which is tested in

turn. The code within the first matching condition is executed. If nothing matches, the code

inside the else condition, if present, is executed. Listing 6-3 (listing6-3.htm in the companion

content) shows code that first checks to see if the inputNum variable contains a number. If

the value is indeed a number, the else if statement performs the checks to make sure the

input value is within the appropriate range. The code calls an appropriate alert() function

based on the matching condition. If you’ve entered a number, then the else condition fires

and displays an alert showing the number.

Listing 6-3  Using an else if and else condition.


"http://www.w3.org/TR/html4/strict.dtd">





An If Example







This is an example from Chapter 6.









128



Part II  Applying JavaScript



In the same way you can use else if and else to test several conditions, you can (sometimes

even must) use multiple levels of conditions. For example, you can test for a certain condition,

and when successful, execute additional conditions. Here’s an example that takes advantage

of the match() function and a regular expression. For more information about regular expressions, see Chapter 4, “Working with Variables and Data Types.”



Using multiple levels of conditionals and a regular expression





1. Open an editor and—if you followed the earlier procedure in this chapter—open the

file you updated, ifexample.htm (in the companion content).



Download from Wow! eBook



The file should have the following code. (If you didn’t follow the earlier example, just

create an empty file, paste in the following code, and go on to the next step.)


"http://www.w3.org/TR/html4/strict.dtd">





An If Example







This is an example from Chapter 6.













2. Save the file with a different file name.







3. In the newly saved file, enter the following code shown in boldface. Note that I’ve

included the changes from the earlier example in boldface:


"http://www.w3.org/TR/html4/strict.dtd">





A Multi-Level Example











Chapter 6  Controlling Flow with Conditionals and Loops



129





This is an example from Chapter 6.













4. Test all these conditions. Start by visiting the page in a web browser. You are prompted

to enter a number. For this first test, type the word , as follows:







5. Click OK. The first if condition matches and then the nested if examines the input. The

input matches the string “four”, resulting in this dialog box:







6. Click OK to close the dialog box. Reload the page. Now type the phrase:



130



Part II  Applying JavaScript







7. Click OK. As with the previous load of the page, the first condition (isNaN()) matches.

However, because the inner if test doesn’t match the phrase pizza, the else condition

of the nested if will match, resulting in this dialog box:







8. Click OK to close the dialog box, and once again, reload the page. This time, type the

numeral 4 into the text box, as follows:







9. Click OK. Now the first if condition fails because the number 4 really is a number.

Therefore, the else if condition is evaluated. Because the number 4 is less than 51

and not greater than 99, the else if condition is a match and displays this alert:







10. Good testing practices dictate that you also test a number above 99. Feel free to do

so. When you’re ready, just click OK to close the dialog box and reload the page once

more. This time, type the number , like this:



Xem Thêm
Tải bản đầy đủ (.pdf) (505 trang)

×