Lecture 6 Part a: JavaScript
G64HLL, High Level Languageshttp://www.cs.nott.ac.uk/~gxo/g64hll
.htmlDr. Gabriela Ochoa
G64HLL, Gabriela Ochoa 2
Previous lecture Basics of java script
The document, window objects The date and math objects How to display data and prompt input How to declare variables Conditionals and loops Arithmetic expressions
G64HLL, Gabriela Ochoa 3
Today Object creation and modification Functions Arrays Constructors Pattern matching Several examples
G64HLL, Gabriela Ochoa 4
Object creation and modification Objects can be created
with new Use the Object
constructor, as in var myObject = new
Object();
The new object has noproperties - a blank object
Properties can be added toan object, any time
var myAirplane = new Object();myAirplane.make = "Cessna";myAirplane.model = "Centurian";
G64HLL, Gabriela Ochoa 5
Functions & Methods Software design: break software into
modules (easier to maintain & debug) Modules JavaScript
Functions Methods (belong to an object) JavaScript includes many useful pre-defined
methods
G64HLL, Gabriela Ochoa 6
Functionsfunction function_name(parameter-list) {
-- declarations and statements–} Arguments separated by commas
E.g. total += parseFloat( s1 + s2 );
We place all function definitions in the head ofthe XHTML document
All variables that are either implicitly declared orexplicitly declared outside functions are global
Variables explicitly declared in a function are local
G64HLL, Gabriela Ochoa 7
Function definitions return statement
Can return either nothing, or a valuereturn expression;
No return statement same as return;
Not returning a value when expected is an error
1 <?xml version = "1.0"?>
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. 10.2: SquareInt.html -->
6 <!-- Square function -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>A Programmer-Defined square Function</title>
11
12 <script type = "text/javascript">
13 <!--
14 document.writeln(
15 "<h1>Square the numbers from 1 to 10</h1>" );
16
17 // square the numbers from 1 to 10
18 for ( var x = 1; x <= 10; ++x )
19 document.writeln( "The square of " + x + " is " +
20 square( x ) + "<br />" );
21
SquareInt.html
Calling function square and passing it the value of x.
•Square two numbers
•loop from 1 to 10
• pass each argument tosquare
22 // The following square function's body is executed
23 // only when the function is explicitly called.
24
25 // square function definition
26 function square( y )
27 {
28 return y * y;
29 }
30 // -->
31 </script>
32
33 </head><body></body>
34 </html>
Variable y gets the value of variable x.
The return statement passes the value of y * yback to the calling function.
•return value of argument multiplied by itself•display result
SquareInt.html
1 <?xml version = "1.0"?>
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. 10.3: maximum.html -->
6 <!-- Maximum function -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Finding the Maximum of Three Values</title>
11
12 <script type = "text/javascript">
13 <!--
14 var input1 =
15 window.prompt( "Enter first number", "0" );
16 var input2 =
17 window.prompt( "Enter second number", "0" );
18 var input3 =
19 window.prompt( "Enter third number", "0" );
20
21 var value1 = parseFloat( input1 );
22 var value2 = parseFloat( input2 );
23 var value3 = parseFloat( input3 );
Prompt for the user to input three integers.
Finding the maximum of 3numbers
• Prompt for 3 inputs• Convert to numbers• Pass to maximum• Math.max
24
25 var maxValue = maximum( value1, value2, value3 );
26
27 document.writeln( "First number: " + value1 +
28 "<br />Second number: " + value2 +
29 "<br />Third number: " + value3 +
30 "<br />Maximum is: " + maxValue );
31
32 // maximum method definition (called from line 25)
33 function maximum( x, y, z )
34 {
35 return Math.max( x, Math.max( y, z ) );
36 }
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>
Call function maximum and pass it the value ofvariables value1, value2 and value3.
Variables x, y and z get the value of variablesvalue1, value2 and value3, respectively.
Method max returns the larger of the twointegers passed to it.
G64HLL, Gabriela Ochoa 12
Arrays Data structures of related items (collections) Dynamic, they grow dynamically Start at zero element Arrays have a length property
Operator new Allocates memory for objects Dynamic memory allocation operator
var c;c = new Array( 12 );
G64HLL, Gabriela Ochoa 13
Arrays Length is dynamic - the length property stores
the length Array objects can be created in two ways, with
new, or by assigning an array literal var myList = new Array(24, "bread", true); var myList2 = [24, "bread", true]; var myList3 = new Array(24);
Because the length property is writeable, you canset it to make the array any length you like, as in myList.length = 150;
SHOW insert_names.js
Arrays
c[ 6 ]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array c[ 0 ]
c[ 1 ]
c[ 2 ]
c[ 3 ]
c[ 11 ]
c[ 10 ]
c[ 9 ]
c[ 8 ]
c[ 7 ]
c[ 5 ]
c[ 4 ]
Position number (indexor subscript) of theelement within array c
Fig. 11.1 A 12-element array.
1 <?xml version = "1.0"?>
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. 11.3: InitArray.html -->
6 <!-- Initializing an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Initializing an Array</title>
11
12 <script type = "text/javascript">
13 <!--
14 // this function is called when the <body> element's
15 // onload event occurs
16 function initializeArrays()
17 {
18 var n1 = new Array( 5 ); // allocate 5-element Array
19 var n2 = new Array(); // allocate empty Array
20
21 // assign values to each element of Array n1
22 for ( var i = 0; i < n1.length; ++i )
23 n1[ i ] = i;
Array n1 has five elements.
The for loop initializes the elements in n1 totheir subscript numbers (0 to 4).
Array n2 is an empty array.
24
25 // create and initialize five-elements in Array n2
26 for ( i = 0; i < 5; ++i )
27 n2[ i ] = i;
28
29 outputArray( "Array n1 contains", n1 );
30 outputArray( "Array n2 contains", n2 );
31 }
32
33 // output "header" followed by a two-column table
34 // containing subscripts and elements of "theArray"
35 function outputArray( header, theArray )
36 {
37 document.writeln( "<h2>" + header + "</h2>" );
38 document.writeln( "<table border = \"1\" width =" +
39 "\"100%\">" );
40
41 document.writeln( "<thead><th width = \"100\"" +
42 "align = \"left\">Subscript</th>" +
43 "<th align = \"left\">Value</th></thead><tbody>" );
The for loop adds five elements to Array n2 andinitialize each element to its subscript number (0 to 4).
Each function displays thecontents of its respective Arrayin an XHTML table.
The first time function ouputArray is called,variable header gets the value of “Array n1contains” and variable theArray gets thevalue of n1.
The second time function ouputArray iscalled, variable header gets the value of“Array n2 contains” and variabletheArray gets the value of n2.
44
45 for ( var i = 0; i < theArray.length; i++ )
46 document.writeln( "<tr><td>" + i + "</td><td>" +
47 theArray[ i ] + "</td></tr>" );
48
49 document.writeln( "</tbody></table>" );
50 }
51 // -->
52 </script>
53
54 </head><body onload = "initializeArrays()"></body>
55 </html>
SumArray.html(1 of 2)
1 <?xml version = "1.0"?>
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. 11.5: SumArray.html -->
6 <!-- Summing Elements of an Array -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Sum the Elements of an Array</title>
11
12 <script type = "text/javascript">
13 <!--
14 function start()
15 {
16 var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
17 var total1 = 0, total2 = 0;
18
19 for ( var i = 0; i < theArray.length; i++ )
20 total1 += theArray[ i ];
21
22 document.writeln( "Total using subscripts: " + total1 );
23
The for loop sums the values contained in the 10-element integer array called theArray.
24 for ( var element in theArray )
25 total2 += theArray[ element ];
26
27 document.writeln( "<br />Total using for...in: " +
28 total2 );
29 }
30 // -->
31 </script>
32
33 </head><body onload = "start()"></body>
34 </html>
Variable element is assigned a subscriptin the range of 0 up to, but not including,theArray.length.
Used to initialize objects, but actually create the properties
function plane(newMake, newModel, newYear){this.make = newMake;this.model = newModel;this.year = newYear;
}
myPlane = new plane("Cessna","Centurnian", "1970");
Can also have method properties
function displayPlane() {document.write("Make: ", this.make,
"<br />");document.write("Model: ", this.model,
"<br />");document.write("Year: ", this.year,
"<br />");}
Now add the following to the constructor: this.display = displayPlane;
Constructors
Pattern Matching
JavaScript provides two ways to do pattern matching:1. Using RegExp objects2. Using methods on String objects
Simple patterns
Two categories of characters in patterns:
a. normal characters (match themselves)
b. metacharacters (can have special meaningsin patterns--do notmatch themselves)
\ | ( ) [ ] { } ^ $ * + ? .
A metacharacter is treated as a normal character if it is backslashed
period is a special metacharacter - it matches any character exceptnewline
G64HLL, Gabriela Ochoa 22
Pattern Matching (continued)
search(pattern)
Returns the position in the object string of the pattern (position isrelative to zero); returns -1 if it fails
var str = "Gluckenheimer";var position = str.search(/n/);/* position is now 6 */
Character classes
• Put a sequence of characters in brackets, and it defines a set ofcharacters, any one of which matches: [abcd]
• Dashes can be used to specify spans of characters in a class: [a-z]• A caret at the left end of a class definition means the opposite: [^0-9]
G64HLL, Gabriela Ochoa 23
Pattern Matching (continued)
• Character class abbreviations
Abbr. Equiv. Pattern Matches
\d [0-9] a digit\D [^0-9] not a digit\w [A-Za-z_0-9] a word character\W [^A-Za-z_0-9] not a word character\s [ \r\t\n\f] a whitespace character\S [^ \r\t\n\f] not a whitespace
characterQuantifiers in braces
Quantifier Meaning
{n} exactly n repetitions{m,} at least m repetitions{m, n} at least m but not more than n
repetitions