1 / 38

Fundamentals of Web-Centric Development

Fundamentals of Web-Centric Development. Presentation 8: JavaScript continued Arrays and objects. This presentation. Overview of JavaScripts support of Arrays Build in objects (Array, String and Date) ”Self declared” objects Examples using Arrays and objects Comments to students:

oral
Download Presentation

Fundamentals of Web-Centric Development

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Fundamentals of Web-Centric Development Presentation 8: JavaScript continued Arrays and objects

  2. This presentation • Overview of JavaScripts support of • Arrays • Build in objects (Array, String and Date) • ”Self declared” objects • Examples using Arrays and objects • Comments to students: • You should know objects and arrays form earlier courses.

  3. Array of data c[ 0 ] -45 Array name c[ 1 ] 6 c[ 2 ] 0 c[ 3 ] 72 AN ARRAY ARE ALWAYS AN OBJECT IN A JAVASCRIPT! - It got methods!! c[ 4 ] 1543 c[ 5 ] -89 c[ 6 ] 0 c[ 7 ] 62 c[ 8 ] -3 c[ 9 ] 1 Position number (index or subscript) of c[ 10 ] 6453 a element in the array c[ 11 ] 78 Fig. 11.1 A 12-element array.

  4. Array object and its methods • Array constructor • var arr1 = new Array(25); • var arr2 = new Array(’first’, ’2.’, ’3’, ’n…); • var value = arr2[1]; (index starts at 0) • value of value becomes ’2.’ • Expansion Dynamic– arr2[arr2.length] = ’New element’; • Dynamic expansion needs more operations! • Methods/properties on array • arr2.length: gives the length on array (here = 4) • arr2.sort() – sorting method on Array object • (prototype, concat, join, pop, push, reverse, shift, slice, unshift)

  5. Arrays as parameter • Arrays get sent by ”Call by reference” • Var arr1 = new Array(’Stefan’, ’Poul Ejnar’); • UndoNameToAllEducators(arr1); • Array elements values sent by ”Call by Value” • Like all ”simple values” i JavaScript • We must sent the Array reference, if we want to change a element globally ex. • arr[1]

  6. Sorting of Arrays • Via method Array.sort • An array are sorted as needed • Default uses is string recognations • ie. 10 comes before 2 • Optional compare functions may be set • Output from this are -1, 0 or 1, dependent on the element value must be moved ahead astern or kept un touched. • Se next page example:

  7. Method sort takes as its optional argument the name of a function that compares two arguments and returns a value of –1, 0 or 1. Function compareIntegers calculates the difference between the integer values of its arguments. 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.8: sort.html --> 6 <!-- Sorting an Array --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Sorting an Array with Array Method sort</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 function start() 15 { 16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 17 18 document.writeln( "<h1>Sorting an Array</h1>" ); 19 outputArray( "Data items in original order: ", a ); 20 a.sort( compareIntegers ); // sort the array 21 outputArray( "Data items in ascending order: ", a ); 22 } 23 24 // outputs "header" followed by the contents of "theArray" 25 function outputArray( header, theArray ) 26 { 27 document.writeln( "<p>" + header + 28 theArray.join( " " ) + "</p>" ); 29 } 30 Sort.html

  8. 31 // comparison function for use with sort 32 function compareIntegers( value1, value2 ) 33 { 34 return parseInt( value1 ) - parseInt( value2 ); 35 } 36 // --> 37 </script> 38 39 </head><body onload = "start()"></body> 40 </html> Sort.htmlPrandram Output

  9. Searching • Known from ALDI (or like) – different models • DEITEL lists: • Linear searching • Binary searching (bi sectioning) • Other algorithms exist • Not really a part of this course NET1 • Though some examples are shown

  10. Arraya is initiated with 100 elements. Array a is populated with the integers 0 to 198. Get value of search key from the input field in the XHTML form. Calling function linearSearch and passing it the Arraya and the value of variable searchKey as an integer. 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.9: LinearSearch.html --> 6 <!-- Linear Search of an Array --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Linear Search of an Array</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var a = new Array( 100 ); // create an Array 15 16 // fill Array with even integer values from 0 to 198 17 for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i; 19 20 // function called when "Search" button is pressed 21 function buttonPressed() 22 { 23 var searchKey = searchForm.inputVal.value; 24 25 // Array a is passed to linearSearch even though it 26 // is a global variable. Normally an array will 27 // be passed to a method for searching. 28 var element = linearSearch( a, parseInt( searchKey ) ); 29 30 if ( element != -1 ) 31 searchForm.result.value = 32 "Found value in element " + element; 33 else 34 searchForm.result.value = "Value not found"; 35 } LinearSearch.html

  11. Function linearSearch compares each each element with a search key. Variable theArray gets the value of Array a and variable key gets the value of variable searchKey. 36 37 // Search "theArray" for the specified "key" value 38 function linearSearch( theArray, key ) 39 { 40 for ( var n = 0; n < theArray.length; ++n ) 41 if ( theArray[ n ] == key ) 42 return n; 43 44 return-1; 45 } 46 // --> 47 </script> 48 49 </head> 50 51 <body> 52 <form name = "searchForm" action = ""> 53 <p>Enter integer search key<br /> 54 <input name ="inputVal"type ="text" /> 55 <input name ="search"type ="button"value ="Search" 56 onclick ="buttonPressed()" /><br /></p> 57 58 <p>Result<br /> 59 <input name ="result"type ="text"size ="30" /></p> 60 </form> 61 </body> 62 </html> LinearSearch.html

  12. Prandram Output

  13. Array a is initiated with 15 elements. Function binarySearch receives two arguments: the Array a and the search key, searchKey. 1 <?xml version = "1.0"?> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 <!-- Fig. 11.10 : BinarySearch.html --> 6 <!-- binary search --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Binary Search</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var a = new Array( 15 ); 15 16 for ( var i = 0; i < a.length; ++i ) 17 a[ i ] = 2 * i; 18 19 // function called when "Search" button is pressed 20 function buttonPressed() 21 { 22 var searchKey = searchForm.inputVal.value; 23 24 searchForm.result.value = 25 "Portions of array searched\n"; 26 27 // Array a is passed to binarySearch even though it 28 // is a global variable. This is done because 29 // normally an array is passed to a method 30 // for searching. 31 var element = 32 binarySearch( a, parseInt( searchKey ) ); 33 BinarySearch.htmlStudy on your own

  14. If the key matches the middle element of a subarray, the subscript of the current element is returned. If key is less than the middle element, the high subscript is set to middle – 1. If key is greater then the middle elements, the high subscript is set to middle +1. 34 if ( element != -1 ) 35 searchForm.result.value += 36 "\nFound value in element " + element; 37 else 38 searchForm.result.value += "\nValue not found"; 39 } 40 41 // Binary search 42 function binarySearch( theArray, key ) 43 { 44 var low = 0; // low subscript 45 var high = theArray.length - 1; // high subscript 46 var middle; // middle subscript 47 48 while ( low <= high ) { 49 middle = ( low + high ) / 2; 50 51 // The following line is used to display the 52 // part of theArray currently being manipulated 53 // during each iteration of the binary 54 // search loop. 55 buildOutput( theArray, low, middle, high ); 56 57 if ( key == theArray[ middle ] ) // match 58 return middle; 59 elseif ( key < theArray[ middle ] ) 60 high = middle - 1; // search low end of array 61 else 62 low = middle + 1; // search high end of array 63 } 64 65 return-1;// searchKey not found 66 } 67 BinarySearch.htmlStudy on your own

  15. Function buildOutput creates the markup that displays the results of the search. 68 // Build one row of output showing the current 69 // part of the array being processed. 70 function buildOutput( theArray, low, mid, high ) 71 { 72 for ( var i = 0; i < theArray.length; i++ ) { 73 if ( i < low || i > high ) 74 searchForm.result.value += " "; 75 // mark middle element in output 76 elseif ( i == mid ) 77 searchForm.result.value += a[ i ] + 78 ( theArray[ i ] < 10 ? "* " : "* " ); 79 else 80 searchForm.result.value += a[ i ] + 81 ( theArray[ i ] < 10 ? " " : " " ); 82 } 83 84 searchForm.result.value += "\n"; 85 } 86 // --> 87 </script> 88 </head> 89 90 <body> 91 <form name = "searchForm" action = ""> 92 <p>Enter integer search key<br /> 93 <input name = "inputVal" type = "text" /> 94 <input name = "search" type = "button" value = 95 "Search" onclick = "buttonPressed()" /><br /></p> 96 <p>Result<br /> 97 <textarea name = "result" rows = "7" cols = "60"> 98 </textarea></p> 99 </form> 100 </body> 101 </html> BinarySearch.htmlStudy on your own

  16. Prandram Output

  17. Objects • JavaScript are object based • NOT object oriented! • It actually is build with another technology-base than Java and C++ (and C#) • No polymorphism • No classes • Two types of objects • Build-in (Implicit) – to ease our work – a kind of API • Self declared (not a main topic here)

  18. Implicit Build-in Objects • Browsers implicit objects • Array • String • Date • Function • Global (incl parseInt) • Math • Number • RegExp

  19. Properties of objects • Objects in Javascript may have both • Properties • Methods • Differences in browsers • Notice: even though that JavaScript has a strong standard compared to DOM, HTML and CSS, then it is a open standard with a free extent of use and interpretations • Cross browser functionality is an important issue • Shiftingleaders

  20. The String object • Strings are fundamental to HTTP and HTML and from this also to JavaScript (every element is a text string) • Manipulation and parsing of strings are a important part of JavaScript • String object gives many functions to this work • Declared both implicit and eksplicit • var streng1 = ”this is a string object”; • var streng 2 = new String(”I am to..”);

  21. String objects methods • Methods divided in two main types • methods to HTML formatting - support for document.write() operations and Dynamic content • methods to parsing and manipultion of strings • Properties • length, prototype • methods • anchor, big, blink, bold, charAt, charCodeAt, concat, fixed, fontcolor, fontsize, fromcharcode, indexOf, italics, lastIndexOf, link, match, replace, search, slice, small, split, strike, sub, substr, substring, sup, toLowerCase, toUpperCase

  22. Examples using a String object • String manipulation • Searching • HTML formatting • Many fold of usages …

  23. Method charAt returns a string containing the character at the specified index (0 in this example). Method charCodeAt returns the Unicode value of the character at the specified index (0 in this example). Method fromCharCode takes a comma-separated list of Unicode values and builds a string containing the character representation of those Unicode values. Methods toLowerCase and toUpperCase display versions of String s2 in all lowercase and all upper case letters, respectively. 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. 12.4: CharacterProcessing.html --> 6 <!-- Character Processing Methods --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Character Processing Methods</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var s = "ZEBRA"; 15 var s2 = "AbCdEfG"; 16 17 document.writeln( "<p>Character at index 0 in '" + 18 s + "' is " + s.charAt( 0 ) ); 19 document.writeln( "<br />Character code at index 0 in '" 20 + s + "' is " + s.charCodeAt( 0 ) + "</p>" ); 21 22 document.writeln( "<p>'" + 23 String.fromCharCode( 87, 79, 82, 68 ) + 24 "' contains character codes 87, 79, 82 and 68</p>" ) 25 26 document.writeln( "<p>'" + s2 + "' in lowercase is '" + 27 s2.toLowerCase() + "'" ); 28 document.writeln( "<br />'" + s2 + "' in uppercase is '" 29 + s2.toUpperCase() + "'</p>" ); 30 // --> 31 </script> 32 33 </head><body></body> 34 </html> CharacterProcessing.html

  24. Prandram Output

  25. Method indexOf determines the first occurrence in the string letters of the string searchForm.inputVal.value. 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. 12.5: SearchingStrings.html --> 6 <!-- Searching Strings --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title> 11 Searching Strings with indexOf and lastIndexOf 12 </title> 13 14 <script type = "text/javascript"> 15 <!-- 16 var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm"; 17 18 function buttonPressed() 19 { 20 searchForm.first.value = 21 letters.indexOf( searchForm.inputVal.value ); 22 searchForm.last.value = 23 letters.lastIndexOf( searchForm.inputVal.value ); 24 searchForm.first12.value = 25 letters.indexOf( searchForm.inputVal.value, 12 ); 26 searchForm.last12.value = 27 letters.lastIndexOf( 28 searchForm.inputVal.value, 12 ); 29 } 30 // --> 31 </script> 32 33 </head> SearchingStrings.html Method lastIndexOf determines the location of the last occurrence in letters of the string in text field inputVal.

  26. 34 <body> 35 <form name = "searchForm" action = ""> 36 <h1>The string to search is:<br /> 37 abcdefghijklmnopqrstuvwxyzabcdefghijklm</h1> 38 <p>Enter substring to search for 39 <input name ="inputVal" type = "text" /> 40 <input name ="search"type ="button"value ="Search" 41 onclick ="buttonPressed()" /><br /></p> 42 43 <p>First occurrence located at index 44 <input name = "first"type ="text"size = "5" /> 45 <br />Last occurrence located at index 46 <input name ="last" type ="text"size ="5" /> 47 <br />First occurrence from index 12 located at index 48 <input name ="first12"type ="text"size ="5" /> 49 <br />Last occurrence from index 12 located at index 50 <input name = "last12"type ="text"size ="5" /></p> 51 </form> 52 </body> 53 </html> SearchingStrings.html

  27. Prandram Output

  28. 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. 12.7: MarkupMethods.html --> 6 <!-- XHTML markup methods of the String object --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>XHTML Markup Methods of the String Object</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var anchorText = "This is an anchor", 15 blinkText = "This is blinking text", 16 fixedText = "This is monospaced text", 17 linkText = "Click here to go to anchorText", 18 strikeText = "This is strike out text", 19 subText = "subscript", 20 supText = "superscript"; 21 22 document.writeln( anchorText.anchor( "top" ) ); 23 document.writeln( "<br />" + blinkText.blink() ); 24 document.writeln( "<br />" + fixedText.fixed() ); 25 document.writeln( "<br />" + strikeText.strike() ); 26 document.writeln( 27 "<br />This is text with a " + subText.sub() ); 28 document.writeln( 29 "<br />This is text with a " + supText.sup() ); 30 document.writeln( 31 "<br />" + linkText.link( "#top" ) ); 32 // --> MarkupMethods.html

  29. Date object • Static object to handling of ”time stamps” • When instantiated a “now” time stamp is put into it • var nu = new Date() • The actual time stamp may also be set manually • var aTimeStamp = new Date(yy, mm, dd, hh, mm, ss) • Lot of constructors with different parametres

  30. Properties of Date object • Properties • prototype • methods • getDate, getDay, getFullYear, getHours, getMilliseconds, getMinutes, getMonth, getSeconds, getTime, getTimezoneOffset, getUTCDate, getUTCDay, getUTCFullYear, getUTCHoursm getUTCMilliseconds, getUTCMinutes, getUTCMonth, getUTCSeconds, getYear, parse, setDate, setFullYear, setHours, setMillieseconds, setMinutes, setSeconds, setTime, setUTCDate, …, tandMTString, toLocaleString, UTC, valueOf, • Examples • Following the use of Date object

  31. 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. 12.9: DateTime.html --> 6 <!-- Date and Time Methods --> 7 8 <html xmlns = "http://www.w3.org/1999/xhtml"> 9 <head> 10 <title>Date and Time Methods</title> 11 12 <script type = "text/javascript"> 13 <!-- 14 var current = new Date(); 15 16 document.writeln( 17 "<h1>String representations and valueOf</h1>" ); 18 document.writeln( "toString: " + current.toString() + 19 "<br />toLocaleString: " + current.toLocaleString() + 20 "<br />toUTCString: " + current.toUTCString() + 21 "<br />valueOf: " + current.valueOf() ); 22 23 document.writeln( 24 "<h1>Get methods for local time zone</h1>" ); 25 document.writeln( "getDate: " + current.getDate() + 26 "<br />getDay: " + current.getDay() + 27 "<br />getMonth: " + current.getMonth() + 28 "<br />getFullYear: " + current.getFullYear() + 29 "<br />getTime: " + current.getTime() + 30 "<br />getHours: " + current.getHours() + 31 "<br />getMinutes: " + current.getMinutes() + 32 "<br />getSeconds: " + current.getSeconds() + 33 "<br />getMilliseconds: " + DateTime.html

  32. 34 current.getMilliseconds() + 35 "<br />getTimezoneOffset: " + 36 current.getTimezoneOffset() ); 37 38 document.writeln( 39 "<h1>Specifying arguments for a new Date</h1>" ); 40 var anotherDate = new Date( 2001, 2, 18, 1, 5, 0, 0 ); 41 document.writeln( "Date: " + anotherDate ); 42 43 document.writeln( 44 "<h1>Set methods for local time zone</h1>" ); 45 anotherDate.setDate( 31 ); 46 anotherDate.setMonth( 11 ); 47 anotherDate.setFullYear( 2001 ); 48 anotherDate.setHours( 23 ); 49 anotherDate.setMinutes( 59 ); 50 anotherDate.setSeconds( 59 ); 51 document.writeln( "Modified date: " + anotherDate ); 52 // --> 53 </script> 54 55 </head><body></body> 56 </html> DateTime.html

  33. Prandram Output

  34. The Number and Boolean objects • Boolean – converts everything to ”true” or ”false” • Implicit given, when all (almost) browsers automatically converts ex. 0 to false and rest to true • var values = new Boolean(onValue); • Number represents both float and int • also implicit given, but may be used to access properties like max value or min value allowed • isNaN useful method (is Not a Number) • methods: valueOf, toString, isNaN

  35. The RegExp object * • Regular Expressions • Used for parsing text strings following certain rules (Regular Expressions), ex if a text field contains 5 cifres, a date or a is formatted like an e-mail adress. • Deitel do not include RegularExpressions under JavaScript • Out of Curriculum • You may look under Pyton • For a tutorial in RegularExpressions to JavaScript see: • http://www.javascriptkit.com/javatutors/re.shtml

  36. A Sample of RegExp in JavaScript <script language="JavaScript1.2"> function checkpostal(){ var re5digit=/^\d{5}$/ //regular expression defining a 5 digit number if (document.myform.myinput.value.search(re5digit)==-1) //if match failed alert("Please enter a valid 5 digit number inside form") } </script> <form name="myform"> <input type="text" name="myinput" size=15> <input type="button" onClick="checkpostal()" value="check"> </form> Checks user input for typing a five ciphers number var re5digit = /^\d{5}$/ - ^: start of string, \d: must be a digit, {5} 5 tal, $: end …search(re5digit) == -1 - search on a string object takes a RegExp as param

  37. Global * • The object that are default for the “browser”. • Has only ”global functions” • “parseInt” as example • Includes • escape, eval, isFinite, isNaN, parseInt, parseFloat, toString, unescape, unwatch, watch, • this • Refers always to current object in the DOM, ex.. to a FORM object • <input type=”text” name=”zip” onChange=”validate(this)”> • Gives you the reference to the form element

  38. Self declared objects • You can declare your own objects • Not like Java C# and C++ • You instantiate an object of type Object, and expands its functionality • Ex. two complex data types … • Var o = new Object(); • Not include in Course Curriculum

More Related