Transcript JavaScript

JavaScript
Part 5
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-byone 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
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">
Initial value of the control
variable
and
Condition to test whether looping
for
should continue
11
<!--
12
// Initialization, repetition condition
13
// incrementing are all included in the
14
// statement header.
15
for ( var counter = 1; counter <= 7; ++counter )
document.writeln( "<p style = \"font-size: " +
16
17
counter + "ex\">XHTML font size " + counter +
18
"ex</p>" );
19
// -->
20
</script>
21
Fig. 8.2 | Countercontrolled repetition
with the for
statement (Part 1 of
2).
Increment to occur after each
iteration of the loop
</head><body></body>
22 </html>
Statement inside the for loop
3
Fig. 8.2 | Counter-controlled repetition with the for statement (Part 2 of 2).
4
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
5
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
13
</style>
14
<script type = "text/javascript">
{ text-align: left }
15
<!--
16
var amount; // current amount of money
17
var principal = 1000.0; // principal amount
18
var rate = .05; // interest rate
19
20
21
22
23
24
25
26
27
28
29
6
document.writeln(
"<table border = \"1\">" ); // begin the table
document.writeln(
"<caption>Calculating Compound Interest</caption>" );
document.writeln(
"<thead><tr><th>Year</th>" ); // year column heading
document.writeln(
"<th>Amount on deposit</th>" ); // amount column heading
document.writeln( "</tr></thead><tbody>" );
Fig. 8.6 | Compound
interest calculation
with a for loop (Part
1 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>" );
} //end for
37
38
39
document.writeln( "</tbody></table>" );
40
// -->
41
</script>
42
</head><body></body>
43 </html>
7
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
Fig. 8.6 | Compound
interest calculation
with a for loop (Part
2 of 2).
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
•
•
•
•
•
•
8
decimal (numbers—the default)
lower-roman (lowercase roman numerals)
upper-roman (uppercase roman numerals)
lower-alpha (lowercase letters)
upper-alpha (uppercase letters)
others
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
9
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
10
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" +
"1 (numbered), 2 (lettered), 3 (roman)", "1" );
19
20
21
switch ( choice )
22
{
23
11
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;
Fig. 8.7 | Using the
switch multipleselection statement
(Part 1 of 4).
case "3":
33
34
startTag = "<ol style = \"list-style-type: upper-roman\">";
35
endTag = "</ol>";
36
listType = "<h1>Roman Numbered
37
break;
default:
38
validInput = false;
39
} //end switch
40
41
42
if ( validInput == true )
43
{
Beginning of statements to be
executed
if choice equals “3”
Statements
List</h1>";
Break out of switch statement
Beginning of statements to be
executed if choice
is anything
Statement
other than “1”, “2” or “3”
document.writeln( listType + startTag );
44
45
for ( var i = 1; i <= 3; ++i )
46
document.writeln( "<li>List item " + i + "</li>"
47
48
document.writeln( endTag );
49
50
} //end if
51
else
document.writeln( "Invalid choice: " + choice );
52
53
// -->
54
</script>
55
</head>
56
<body>
57
58
<p>Click Refresh (or Reload) to run the script again</p>
</body>
59 </html>
12
Fig. 8.7 | Using the
switch multipleselection statement
(Part 2 of 4).
No break is necessary, since we’ve
come to the end of the switch
);
anyway
Fig. 8.7 | Using the switch multipleselection statement (Part 3 of 4).
13
Fig. 8.7 | Using the switch
multiple-selection statement (Part
4 of 4).
14
9.1 Introduction
• To develop and maintain a large program
• construct it from small, simple pieces
• divide and conquer
15
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.
16
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.
17
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,…)
18
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
19
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
20
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
21
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 is
function function-name( parameter-list )
{
declarations and statements
}
22
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
23
1
2
<!DOCTYPE html>
3
Fig. 9.2 | Programmerdefined function
square (Part 1 of 2).
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++ )
document.writeln( "The square of " + x + " is " +
16
square( x ) + "<br />" );
17
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
{
return y * y;
25
26
} // end function square
27
// -->
28
</script>
29
End
</head><body></body>
30 </html>
24
function square
Calls function square with x as
an argument, which will return the
value to be inserted here
Begin function square
Names the parameter y
Returns the value of y * y
(the argument squared) to the
caller
Fig. 9.2 | Programmer-defined function square (Part 2 of 2).
25
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
26
1
2
3
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Fig. 9.4 | Random
integers, shifting
and scaling (Part 1
of 2).
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
Shifts the range of
return values up by 1
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
30
27
Scales the range of return values
by a factor of 6
31
document.writeln( "</tr><tr>" );
} // end for
Takes the floor of the number
from 1.0 up to, but not
including, 7.0
32
document.writeln( "</tr></table>" );
33
// -->
34
</script>
35
</head>
36
<body>
37
38
<p>Click Refresh (or Reload) to run the script again</p>
</body>
Fig. 9.4 | Random
integers, shifting
and scaling (Part 2
of 2).
39 </html>
Variable value has a value from
1 to 6
28
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
29
1
2
<!DOCTYPE html>
Fig. 9.7 | Random
image generation
using
Math.random.
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 = \"" +
Math.floor( 1 + Math.random() * 7 ) +
13
14
// -->
15
</script>
16
</head>
17
<body>
18
19
<p>Click Refresh (or Reload) to run the script again</p>
</body>
20 </html>
30
".gif\" />" );
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
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
31
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.
32