Lecture 6 Part a: JavaScript G64HLL, High Level Languages http://www.cs.nott.ac.uk/~gxo/g64hll.html Dr. Gabriela Ochoa gxo@cs.nott.ac.uk
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 2
Today Object creation and modification Functions Arrays Constructors Pattern matching Several examples G64HLL, Gabriela Ochoa 3
Object creation and modification Objects can be created with new Use the Object constructor, as in var myobject = new Object(); The new object has no properties - a blank object Properties can be added to an object, any time var myairplane = new Object(); myairplane.make = "Cessna"; myairplane.model = "Centurian"; G64HLL, Gabriela Ochoa 4
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 5
Functions function 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 of the XHTML document All variables that are either implicitly declared or explicitly declared outside functions are global Variables explicitly declared in a function are local G64HLL, Gabriela Ochoa 6
Function definitions return statement Can return either nothing, or a value return expression; No return statement same as return; Not returning a value when expected is an error G64HLL, Gabriela Ochoa 7
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 Square two numbers loop from 1 to 10 pass each argument to square Calling functionsquare and passing it the value ofx.
22 // The following square function's body is executed 23 // only when the function is explicitly called. 24 25 // square function definition Variableygets the value of variablex. SquareInt.html 26 function square( y ) 27 { 28 return y * y; 29 } 30 // --> 31 </script> 32 Thereturn statement passes the value ofy*y back to the calling function. 33 </head><body></body> 34 </html> return value of argument multiplied by itself display result
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 3 numbers 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 functionmaximum and pass it the value of variablesvalue1,value2 andvalue3. Methodmax returns the larger of the two integers passed to it. Variablesx,yandzget the value of variables value1,value2 andvalue3, respectively.
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 12
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 can set it to make the array any length you like, as in mylist.length = 150; SHOW insert_names.js G64HLL, Gabriela Ochoa 13
Arrays Name of array Position number (index or subscript) of the element within arrayc c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 4 ] c[ 5 ] c[ 6 ] c[ 7 ] c[ 8 ] c[ 9 ] c[ 10 ] c[ 11 ] -45 6 0 72 1543-89 0 62-3 1 6453 78 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; Arrayn1 has five elements. Arrayn2 is an empty array. Thefor loop initializes the elements inn1 to their subscript numbers (0 to 4).
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 The second first time time functionouputarray is called, is called, variableheader variableheader gets thegets value theof Array value n1 Array contains n2 and contains variablethearray and variable gets the thearray value ofn1. gets the value ofn2. 41 document.writeln( "<thead><th width = \"100\"" + 42 "align = \"left\">subscript</th>" + 43 "<th align = \"left\">value</th></thead><tbody>" ); Thefor loop adds five Each elements function toarrayn2 displays theand initialize each element contents to its subscript of its respective number Array (0 to 4). in an XHTML table.
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>
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 SumArray.html 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> (1 of 2) 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 Thefor loop sums the values contained in the 10- element integer array calledthearray.
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> Variableelement is assigned a subscript in the range of 0 up to, but not including, thearray.length.
Constructors 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;
Pattern Matching JavaScript provides two ways to do pattern matching: 1. Using RegExp objects 2. 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 not match themselves) \ ( ) [ ] { } ^ $ * +?. A metacharacter is treated as a normal character if it is backslashed period is a special metacharacter - it matches any character except newline
Pattern Matching (continued) search(pattern) Returns the position in the object string of the pattern (position is relative 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 of characters, any one of which matches: [abcd] Dashes can be used to specify spans of characters in a class: A caret at the left end of a class definition means the opposite: [a-z] [^0-9] G64HLL, Gabriela Ochoa 22
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 character Quantifiers in braces Quantifier {n} {m,} {m, n} Meaning exactly n repetitions at least m repetitions at least m but not more than n repetitions G64HLL, Gabriela Ochoa 23
Example (forms_check.html) Common uses of JavaScript: check the format of input from HTML forms This example shows: use of a simple function to check that an input has the correct format of a telephone number G64HLL, Gabriela Ochoa 24