1. Trang chủ
  2. » Công Nghệ Thông Tin

Simply JavaScript phần 5 ppt

15 135 0

Đ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

Nội dung

var postcodes = []; postcodes["Armadale"] = 3143; postcodes["North Melbourne"] = 3051; postcodes["Camperdown"] = 2050; postcodes["Annandale"] = 2038; Now that we’ve created our associative array, it’s not hard to get the postcode for Annandale. All we have to do is specify the right key, and the value will appear: alert(postcodes["Annandale"]); The resulting alert is shown in Figure 2.7. Figure 2.7. Finding a postcode using an associative array Although the keys for an associative array have to be strings, the values can be of any data type, including other arrays or associative arrays. Conditions and Loops: Controlling Program Flow So far, we’ve seen statements that allow you to set and retrieve variables inside your program. For a program to be really useful, however, it has to be able to make de- cisions based on the values of those variables. The way we make those decisions is through the use of special structures called conditions and loops, which help to control which parts of your program will run under particular conditions, and how many times those parts will be run. Order the print version of this book to get all 400+ pages! 35Programming with JavaScript Conditions: Making Decisions If you think of your program as being like a road map, and the browser as a car navigating those roads, you’ll realize that the browser has to be able to take different paths depending on where the user wants to go. Although a program might seem like a linear path—one statement following another—conditional statements act like intersections, allowing you to change directions on the basis of a given condition. if Statements The most common conditional statement is an if statement. An if statement checks a condition, and if that condition is met, allows the program to execute some code. If the condition isn’t met, the code is skipped. The flow of a program through an if statement can be visualized as in Figure 2.8. Figure 2.8. The logical flow of an if statement Simply JavaScript (www.sitepoint.com) Simply JavaScript36 Written as code, if statements take this form: if (condition) { conditional code; } Instead of a semicolon, an if statement ends with the conditional code between curly braces ({…}). 2 It’s considered best practice to put each of these braces on its own line, to make it as easy as possible to spot where blocks of code begin and end. Indenting Code It’s standard practice to indent the code that’s inside curly braces. On each indented line, a standard number of spaces or tab characters should appear before the first character of the statement. This helps to improve the readability of your code and makes it easier to follow the flow of your programs. We use two spaces as the standard indentation in this book, but you can use four spaces, one tab—whatever looks best to you. Just be consistent. Every time you nest curly braces (for instance, in another if statement inside a block of condi- tional code), you should increase the indentation for the nested lines by one standard indent. The condition has to be contained within round brackets (also called parentheses) and will be evaluated as a Boolean, with true meaning the code between the curly braces will be executed and false indicating it will be skipped. However, the con- dition doesn’t have to be an explicit Boolean value—it can be any expression that evaluates to a value that’s able to be used as a Boolean. Expressions An expression is a combination of values, variable references, operators, and function calls that, when evaluated, produce another value. Wherever a JavaScript value (like a number or a string) is expected, you can use an expression instead. 2 If the conditional code consists of just one statement, you can choose to omit the curly braces. I find it clearer to always include the braces, which is what we’ll do in this book. Order the print version of this book to get all 400+ pages! 37Programming with JavaScript Here’s a simple expression: 4 + 6 When evaluated, it produces a value (10). We can write a statement that uses this expression like so: var effect = 4 + 6; We now have in our program a variable called effect, with a value of 10. With conditional statements, the most useful types of expressions are those that use comparison operators to test a condition and return a Boolean value indicating its outcome. You might remember comparison operators such as greater than (>) and less than (<) from some of your old mathematics classes, but there are also equality (==) and inequality (!=) operators, and various combinations of these. Basically, each com- parison operator compares what’s on the left of the operator with what’s on the right, then evaluates to true or false. You can then use that result in a conditional statement like this: var age = 27; if (age > 20) { alert("Drink to get drunk"); } The greater than and less than operators are really only useful with numbers, because it feels a bit too Zen to ask “is one string greater than another?” However, the equality operator (==) is useful with both strings and numbers: var age = 27; if (age == 50){ alert("Half century"); } Simply JavaScript (www.sitepoint.com) Simply JavaScript38 var name = "Maximus"; if (name == "Maximus") { alert("Good afternoon, General."); } In the first condition, age is 27 and we’re testing whether it is equal to 50; obviously, this condition will evaluate to false, so the conditional code will not be run. In the second condition, name is "Maximus" and we’re testing whether it is equal to "Maximus". This condition will evaluate to true and the conditional code will be executed. == versus = Be careful to use two equals signs rather than one when you intend to check for equality. If you use only one, you’ll be assigning the value on the right to the variable on the left, rather than comparing them, so you’ll end up losing your original value rather than checking it! We can reverse the equality test by using the inequality operator (!=): var name = "Decimus"; if (name != "Maximus") { alert("You are not allowed in."); } Now, because name is "Decimus" and we’re testing whether it isn’t equal to "Maximus" that condition will evaluate to true and the conditional code will be run. Table 2.1 lists the most commonly used comparison operators, and the results they’ll return with different values: Order the print version of this book to get all 400+ pages! 39Programming with JavaScript Table 2.1. Commonly Used Comparison Operators ResultExampleOperator true if A is greater than BA > B> true if A is greater than or equal to BA >= B>= true if A is less than BA < B< true if A is less than or equal to BA <= B<= true if A equals BA == B== true if A does not equal BA != B!= true if A’s Boolean value is false!A! Multiple Conditions Instead of using just one test as a condition, you can create a whole chain of them using the logical operators AND (&&) and OR (||). 3 Both of these operators may be used to combine conditional tests. The AND operator specifies that both tests must evaluate to true in order for the whole expression to evaluate to true. The OR operator specifies that only one of the tests has to evaluate to true in order for the whole expression to evaluate to true. Take a look at this conditional statement: var age = 27; if (age > 17 && age < 21) { alert("Old enough to vote, too young to drink"); } Here, age is greater than 17 but it’s not less than 21, so, since one of the tests evalu- ated to false, the entire condition evaluates to false. This is a good way to check if a number falls within a specific range. On the other hand, the OR operator is good for checking whether a variable matches one of a few values: 3 That’s two vertical bars, not lowercase Ls or number 1s. Simply JavaScript (www.sitepoint.com) Simply JavaScript40 var sport = "Skydiving"; if (sport == "Bungee jumping" || sport == "Cliff diving" || sport == "Skydiving") { alert("You're extreme!"); } Although the first two tests in this expression evaluate to false, sport matches the last test in the OR expression, so the whole condition will evaluate to true. if-else Statements An if statement allows you to execute some code when a condition is met, but doesn’t offer any alternative code for cases when the condition isn’t met. That’ s the purpose of the else statement. In an if-else statement, you begin just as you would for an if statement, but im- mediately after the closing brace of the if, you include an else, which specifies code to be executed when the condition of the if statement fails: if (condition) { conditional code; } else { alternative conditional code; } The flow of this construct can be visualized as shown in Figure 2.9. To provide some alternative code, all you have to do is append an else statement to the end of the if: var name = "Marcus"; if (name == "Maximus") { alert("Good afternoon, General."); } Order the print version of this book to get all 400+ pages! 41Programming with JavaScript Figure 2.9. The logical flow of an if-else statement else { alert("You are not allowed in."); } This approach saves you from creating a separate if statement with a negative for- mulation of the original condition. else-if Statements Technically speaking, else-if isn’t a separate type of statement from if-else, but you should be aware of it, because it can be quite useful. Simply JavaScript (www.sitepoint.com) Simply JavaScript42 If you want to provide some alternative code for cases in which an if statement fails, but you want to further assess the data in order to decide what course of action to take, an else-if statement is what you need. Instead of just typing else, type else if, followed by the extra condition you want to test: var name = "Marcus"; if (name == "Maximus") { alert("Good afternoon, General."); } else if (name == "Marcus") { alert("Good afternoon, Emperor."); } else { alert("You are not allowed in."); } You can chain together as many else-if statements as you want, and at the end, you can include a normal else statement for use when everything fails (though it’s not necessary). Loops: Minimizing Repetition Computers are meant to make life easier, right? Well, where are those darn robot servants, huh? Luckily, computers have a few capabilities that will save you thinking and typing time when you’re programming. The most effective of these are loops, which auto- mate repetitive tasks like modifying each element in an array. There are a couple of different loop statements but they essentially do the same thing: repeat a set of actions for as long as a specified condition is true. while Loops while is the simplest of the loops. All it needs is a condition, and some conditional code: Order the print version of this book to get all 400+ pages! 43Programming with JavaScript while (condition) { conditional code; } When the program first encounters the while loop, it checks the condition. If the condition evaluates to true, the conditional code will be executed. When the pro- gram reaches the end of the conditional code, it goes back up to the condition, checks it, and if it evaluates to true, the conditional code will be executed … and so on, as Figure 2.10 shows. A while loop only finishes when its condition evaluates to false. This means it’s important to have something inside the conditional code that will affect the condi- tion, eventually making it evaluate to false. Otherwise, your program will never escape the while loop, and will repeat the conditional code forever, causing the browser to become unresponsive. 4 Loops are extremely handy when they’re used in conjunction with arrays, because they allow you to step sequentially through the array and perform the same operation on each element. To step through an array with a while loop, you need an incrementing counter that starts at 0 and increases by one each time the loop executes. This incrementer will keep track of the index of the element that we’re currently working with. When we reach the end of the array, we need to make it stop—that’s where we use the array’ s length property. In this example, we’ll multiply each element of the numbers array by two: var numbers = [1, 2, 3, 4, 5]; var incrementer = 0; while (incrementer < numbers.length) { numbers[incrementer] *= 2; incrementer++; } 4 In Firefox, the browser will eventually display a message to the user complaining that your script is taking a long time to execute. Oh, the shame! Simply JavaScript (www.sitepoint.com) Simply JavaScript44 [...]... numbers[i] *= 2; i++; } With a for loop, you can reduce the code above to: 5 The co-author wishes it noted that he uses them all the time … possibly just because he likes to show off Simply JavaScript (www.sitepoint.com) Programming with JavaScript 47 Figure 2.11 The logical flow of a do-while loop var numbers = [1, 2, 3, 4, 5] ; for (var i = 0; i < numbers.length; i++) { numbers[i] *= 2; } A for loop... tells the program that you’re defining a new function, and that the code contained between the curly braces that follow should be executed whenever that function is called: Simply JavaScript (www.sitepoint.com) Programming with JavaScript 49 Figure 2.12 The logical flow of a for loop function warning() { alert("This is your final warning"); } Order the print version of this book to get all 400+ pages!... I’ve used one in ten years of programming .5 Your friends and family will be impressed if you know about them, though for Loops for loops are my favorite kind of loops—they’re so succinct! They’re a lot like while loops, but they offer a couple of handy shortcuts for statements that we commonly use with loops Consider this while loop: var numbers = [1, 2, 3, 4, 5] ; var i = 0; while (i < numbers.length)...Programming with JavaScript 45 Figure 2.10 The logical flow of a while loop The conditional code inside that while loop uses incrementer as the index for the array Starting at 0, this variable will reference the first element,... semicolons The first statement is the declaration It allows us to declare a counter variable—in this case i—and set its initial value Order the print version of this book to get all 400+ pages! 48 Simply JavaScript The second statement is the condition that controls the loop Just like the condition in a while loop, this condition must evaluate to true in order for the conditional code to be executed... to put your code into functions Functions are like little packages of JavaScript code waiting to be called into action You’ve seen one function already in this chapter—the alert function we used to pop up an alert box in the browser alert is a function that’s native to all browsers—that means it comes built-in with the browser’s JavaScript interpreter—but it’s possible to create your own functions,... increments inside a loop This variable is often called a counter variable, because it counts how many times the loop has been executed Order the print version of this book to get all 400+ pages! 46 Simply JavaScript do-while Loops A do-while loop behaves almost identically to a while loop, with one key difference: the conditional code is placed before the condition, so the conditional code is always... decrement) the counter, but you could theoretically put anything in there A for loop can be thought to exhibit a flow similar to that shown in Figure 2.12 Functions: Writing Code for Later So far, all the JavaScript code we’ve seen (and you’ve perhaps tried out) executes as soon as the page loads in your browser It runs from top to bottom and then stops, never to run again (at least, until the page is reloaded) . with both strings and numbers: var age = 27; if (age == 50 ){ alert("Half century"); } Simply JavaScript (www.sitepoint.com) Simply JavaScript3 8 var name = "Maximus"; if (name. because he likes to show off. Simply JavaScript (www.sitepoint.com) Simply JavaScript4 6 Figure 2.11. The logical flow of a do-while loop var numbers = [1, 2, 3, 4, 5] ; for (var i = 0; i < numbers.length;. a few values: 3 That’s two vertical bars, not lowercase Ls or number 1s. Simply JavaScript (www.sitepoint.com) Simply JavaScript4 0 var sport = "Skydiving"; if (sport == "Bungee

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