javascript part 5. 2 8.3 for repetition statement for statement cpecifies each of the items needed...

32
JavaScript Part 5

Upload: julius-thomas

Post on 15-Jan-2016

231 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

JavaScriptPart 5

Page 2: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

2

8.3 for Repetition Statement

• for statement • Cpecifies each of the items needed for counter-controlled repetition with a control variable• Can use a block to put multiple statements into the body

• If the loop’s condition uses a < or > instead of a <= or >=, or vice-versa, it can result in an off-by-one error

• for statement takes three expressions• Initialization• Condition • Increment Expression

• The increment expression in the for statement acts like a stand-alone statement at the end of the body of the for statement

• Place only expressions involving the control variable in the initialization and increment sections of a for statement

Page 3: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

3

Fig. 8.2 | Counter-controlled repetition with the for statement (Part 1 of 2).

1

2 <!DOCTYPE html>

3

4

5 <!-- Fig. 8.2: ForCounter.html -->

6 <!-- Counter-controlled repetition with the for statement. -->

7 <html>

8 <head>

9 <title>Counter-Controlled Repetition</title>

10 <script type = "text/javascript">

11 <!--

12 // Initialization, repetition condition and

13 // incrementing are all included in the for

14 // statement header.

15 for ( var counter = 1; counter <= 7; ++counter )

16 document.writeln( "<p style = \"font-size: " +

17 counter + "ex\">XHTML font size " + counter +

18 "ex</p>" );

19 // -->

20 </script>

21 </head><body></body>

22 </html>

Initial value of the control variable

Condition to test whether looping should continue

Increment to occur after each iteration of the loop

Statement inside the for loop

Page 4: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

4

Fig. 8.2 | Counter-controlled repetition with the for statement (Part 2 of 2).

Page 5: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

5

8.3 for Repetition Statement (Cont.)• The three expressions in the for statement are optional• The two semicolons in the for statement are required• The initialization, loop-continuation condition and increment portions

of a for statement can contain arithmetic expressions

Page 6: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

6

Fig. 8.6 | Compound interest calculation with a for loop (Part 1 of 2).

1

2 <!DOCTYPE html>

3

4

5 <!-- Fig. 8.6: Interest.html -->

6 <!-- Compound interest calculation with a for loop. -->

7 <html>

8 <head>

9 <title>Calculating Compound Interest</title>

10 <style type = "text/css">

11 table { width: 100% }

12 th { text-align: left }

13 </style>

14 <script type = "text/javascript">

15 <!--

16 var amount; // current amount of money

17 var principal = 1000.0; // principal amount

18 var rate = .05; // interest rate

19

20 document.writeln(

21 "<table border = \"1\">" ); // begin the table

22 document.writeln(

23 "<caption>Calculating Compound Interest</caption>" );

24 document.writeln(

25 "<thead><tr><th>Year</th>" ); // year column heading

26 document.writeln(

27 "<th>Amount on deposit</th>" ); // amount column heading

28 document.writeln( "</tr></thead><tbody>" );

29

Page 7: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

7

Fig. 8.6 | Compound interest calculation with a for loop (Part 2 of 2).

30 // output a table row for each year

31 for ( var year = 1; year <= 10; ++year )

32 {

33 amount = principal * Math.pow( 1.0 + rate, year );

34 document.writeln( "<tr><td>" + year +

35 "</td><td>" + amount.toFixed(2) +

36 "</td></tr>" );

37 } //end for

38

39 document.writeln( "</tbody></table>" );

40 // -->

41 </script>

42 </head><body></body>

43 </html>

Control variable year begins with a value of 1

Continue to execute the loop while year is less than or equal to 10

After each loop iteration, increase the value of year by 1

Page 8: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

8

8.5 switch Multiple-Selection Statement

• switch multiple-selection statement • Tests a variable or expression separately for each of the values it may assume• Different actions are taken for each value

• CSS property list-style-type • Allows you to set the numbering system for a list• Possible values include

• decimal (numbers—the default)• lower-roman (lowercase roman numerals)• upper-roman (uppercase roman numerals)• lower-alpha (lowercase letters)• upper-alpha (uppercase letters)• others

Page 9: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

9

8.5 switch Multiple-Selection Statement (Cont.)

• switch statement • Consists of a series of case labels and an optional default case• When control reaches a switch statement

• The script evaluates the controlling expression in the parentheses • Compares this value with the value in each of the case labels• If the comparison evaluates to true, the statements after the case label are executed in order until a break

statement is reached

• The break statement is used as the last statement in each case to exit the switch statement immediately• The default case allows you to specify a set of statements to execute if no

other case is satisfied• Usually the last case in the switch statement

Page 10: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

10

8.5 switch Multiple-Selection Statement (Cont.)

• Each case can have multiple actions (statements)• Braces are not required around multiple actions in a case of a switch• The break statement is not required for the last case because program control

automatically continues with the next statement after the switch• Having several case labels listed together (e.g., case 1: case 2: with no

statements between the cases) executes the same set of actions for each case

Page 11: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

11

Fig. 8.7 | Using the switch multiple-selection statement (Part 1 of 4).

1

2 <!DOCTYPE html>

3

4

5 <!-- Fig. 8.7: SwitchTest.html -->

6 <!-- Using the switch multiple-selection statement. -->

7 <html>

8 <head>

9 <title>Switching between XHTML List Formats</title>

10 <script type = "text/javascript">

11 <!--

12 var choice; // user’s choice

13 var startTag; // starting list item tag

14 var endTag; // ending list item tag

15 var validInput = true; // indicates if input is valid

16 var listType; // type of list as a string

17

18 choice = window.prompt( "Select a list style:\n" +

19 "1 (numbered), 2 (lettered), 3 (roman)", "1" );

20

21 switch ( choice )

22 {

23 case "1":

24 startTag = "<ol>";

25 endTag = "</ol>";

26 listType = "<h1>Numbered List</h1>";

27 break;

28 case "2":

29 startTag = "<ol style = \"list-style-type: upper-alpha\">";

30 endTag = "</ol>";

31 listType = "<h1>Lettered List</h1>";

32 break;

Page 12: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

12

Fig. 8.7 | Using the switch multiple-selection statement (Part 2 of 4).

33 case "3":

34 startTag = "<ol style = \"list-style-type: upper-roman\">";

35 endTag = "</ol>";

36 listType = "<h1>Roman Numbered List</h1>";

37 break;

38 default:

39 validInput = false;

40 } //end switch

41

42 if ( validInput == true )

43 {

44 document.writeln( listType + startTag );

45

46 for ( var i = 1; i <= 3; ++i )

47 document.writeln( "<li>List item " + i + "</li>" );

48

49 document.writeln( endTag );

50 } //end if

51 else

52 document.writeln( "Invalid choice: " + choice );

53 // -->

54 </script>

55 </head>

56 <body>

57 <p>Click Refresh (or Reload) to run the script again</p>

58 </body>

59 </html>

Break out of switch statement

Beginning of statements to be executed if choice equals “3”

Beginning of statements to be executed if choice is anything other than “1”, “2” or “3”

No break is necessary, since we’ve come to the end of the switch anyway

Statements

Statement

Page 13: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

13

Fig. 8.7 | Using the switch multiple-selection statement (Part 3 of 4).

Page 14: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

14

Fig. 8.7 | Using the switch multiple-selection statement (Part 4 of 4).

Page 15: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

15

9.1 Introduction

• To develop and maintain a large program • construct it from small, simple pieces• divide and conquer

Page 16: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

16

9.2 Program Modules in JavaScript

• JavaScript programs are written by combining• new functions that the programmer writes• with “prepackaged” functions and objects available in JavaScript

• The term method implies that a function belongs to a particular object

• We refer to functions that belong to a particular JavaScript object as methods; all others are referred to as functions.

Page 17: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

17

9.2 Program Modules in JavaScript (Cont.)

• JavaScript provides several objects that have a rich collection of methods for • mathematical calculations, • string manipulations, • date and time manipulations, • manipulations of collections of data called arrays.

• Whenever possible, use existing JavaScript objects, methods and functions instead of writing new ones. • This reduces script-development time and helps avoid introducing errors.

Page 18: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

18

9.2 Program Modules in JavaScript (Cont.)

• Functions are invoked by writing the name of the function, followed by a left parenthesis, followed by a comma-separated list of zero or more arguments, followed by a right parenthesis

function(argument1,argument2,…)

Page 19: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

19

9.2 Program Modules in JavaScript (Cont.)

• Methods are called in the same way as functions, but require the name of the object to which the method belongs and a dot preceding the method name

Objectname.method(argument1,argument2,…)

Example:Document.write(“<h1>Hello1</h1>”)

• Function (and method) arguments may be constants, variables or expressions

Page 20: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

20

9.3 Programmer-Defined Functions

• Variables declared in function definitions are local variables• they can be accessed only in the function in which they are defined

• A function’s parameters are considered to be local variables

• When a function is called, the arguments in the call are assigned to the corresponding parameters in the function definition

Page 21: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

21

9.3 Programmer-Defined Functions (Cont.)

• Code that is packaged as a function can be executed from several locations in a program by calling the function.

• Each function should perform a single, well-defined task, and the name of the function should express that task effectively • Promotes software reusability

Page 22: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

22

9.4 Function Definitions

• return statement • passes information from inside a function back to the point in the program where it was called

• The format of a function definition isfunction function-name( parameter-list )

{

declarations and statements

}

Page 23: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

23

9.4 Function Definitions (Cont.)

• Three ways to return control to the point at which a function was invoked• Reaching the function-ending right brace • Executing the statement return;• Executing the statement “return expression;” to return the value of expression to the caller

• When a return statement executes, control returns immediately to the point at which the function was invoked

Page 24: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

24

Fig. 9.2 | Programmer-defined function square (Part 1 of 2).

1

2 <!DOCTYPE html>

3

4

5 <!-- Fig. 9.2: SquareInt.html -->

6 <!-- Programmer-defined function square. -->

7 <html>

8 <head>

9 <title>A Programmer-Defined square Function</title>

10 <script type = "text/javascript">

11 <!--

12 document.writeln( "<h1>Square the numbers from 1 to 10</h1>" );

13

14 // square the numbers from 1 to 10

15 for ( var x = 1; x <= 10; x++ )

16 document.writeln( "The square of " + x + " is " +

17 square( x ) + "<br />" );

18

19 // The following square function definition is executed

20 // only when the function is explicitly called.

21

22 // square function definition

23 function square( y )

24 {

25 return y * y;

26 } // end function square

27 // -->

28 </script>

29 </head><body></body>

30 </html>

Calls function square with x as an argument, which will return the value to be inserted here

Begin function square

Returns the value of y * y (the argument squared) to the caller

End function squareNames the parameter y

Page 25: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

25

Fig. 9.2 | Programmer-defined function square (Part 2 of 2).

Page 26: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

26

9.5 Random Number Generation

• Method random generates a floating-point value from 0.0 up to, but not including, 1.0• Random integers in a certain range can be generated by scaling and shifting the

values returned by random, then using Math.floor to convert them to integers• The scaling factor determines the size of the range (i.e. a scaling factor of 4 means four possible

integers)• The shift number is added to the result to determine where the range begins (i.e. shifting the numbers

by 3 would give numbers between 3 and 7)

• Method Math.floor rounds its argument down to the closest integer

Page 27: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

27

Fig. 9.4 | Random integers, shifting and scaling (Part 1 of 2).

1

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

4

5 <!-- Fig. 9.4: RandomInt.html -->

6 <!-- Random integers, shifting and scaling. -->

7 <html>

8 <head>

9 <title>Shifted and Scaled Random Integers</title>

10 <style type = "text/css">

11 table { width: 50%;

12 border: 1px solid gray;

13 text-align: center }

14 </style>

15 <script type = "text/javascript">

16 <!--

17 var value;

18

19 document.writeln( "<table>" );

20 document.writeln( "<caption>Random Numbers</caption><tr>" );

21

22 for ( var i = 1; i <= 20; i++ )

23 {

24 value = Math.floor( 1 + Math.random() * 6 );

25 document.writeln( "<td>" + value + "</td>" );

26

27 // start a new table row every 5 entries

28 if ( i % 5 == 0 && i != 20 )

29 document.writeln( "</tr><tr>" );

30 } // end for

31

Shifts the range of return values up by 1

Scales the range of return values by a factor of 6

Takes the floor of the number from 1.0 up to, but not including, 7.0

Page 28: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

28

Fig. 9.4 | Random integers, shifting and scaling (Part 2 of 2).

32 document.writeln( "</tr></table>" );

33 // -->

34 </script>

35 </head>

36 <body>

37 <p>Click Refresh (or Reload) to run the script again</p>

38 </body>

39 </html>

Variable value has a value from 1 to 6

Page 29: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

29

9.7 Another Example: Random Image Generator

• We can use random number generation to randomly select from a number of images in order to display a random image each time a page loads

Page 30: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

30

Fig. 9.7 | Random image generation using Math.random.

1

2 <!DOCTYPE html>

3

4

5 <!-- Fig. 9.7: RandomPicture.html -->

6 <!-- Random image generation using Math.random. -->

7 <html>

8 <head>

9 <title>Random Image Generator</title>

10 <script type = "text/javascript">

11 <!--

12 document.write ( "<img src = \"" +

13 Math.floor( 1 + Math.random() * 7 ) + ".gif\" />" );

14 // -->

15 </script>

16 </head>

17 <body>

18 <p>Click Refresh (or Reload) to run the script again</p>

19 </body>

20 </html>

Creates an src attribute by concatenating a random integer from 1 to 7 with “.gif” to reference one of the images 1.gif, 2.gif, 3.gif, 4.gif, 5.gif, 6.gif or 7.gif

Page 31: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

31

9.8 Scope Rules

• Each identifier in a program has a scope• The scope of an identifier for a variable or function is the portion of

the program in which the identifier can be referenced• Global variables or script-level are accessible in any part of a script

and are said to have global scope• Thus every function in the script can potentially use the variables

Page 32: JavaScript Part 5. 2 8.3 for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable

32

9.8 Scope Rules (Cont.)

• Identifiers declared inside a function have function (or local) scope and can be used only in that function• Function scope begins with the opening left brace

({) of the function in which the identifier is declared and ends at the terminating right brace (}) of the function• Local variables of a function and function

parameters have function scope• If a local variable in a function has the same name as

a global variable, the global variable is “hidden” from the body of the function.