Presentation is loading. Please wait.

Presentation is loading. Please wait.

Presentation 8: JavaScript continued Arrays and objects Internet Technology 1.

Similar presentations


Presentation on theme: "Presentation 8: JavaScript continued Arrays and objects Internet Technology 1."— Presentation transcript:

1 Presentation 8: JavaScript continued Arrays and objects Internet Technology 1

2 Ingeniørhøjskolen i Århus Slide 2 of 38 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 Ingeniørhøjskolen i Århus Slide 3 of 38 Array of data c[ 6 ] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Array name c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 11 ] c[ 10 ] c[ 9 ] c[ 8 ] c[ 7 ] c[ 5 ] c[ 4 ] Position number (index or subscript) of a element in the array Fig. 11.1A 12-element array. AN ARRAY ARE ALWAYS AN OBJECT IN A JAVASCRIPT! - It got methods!!

4 Ingeniørhøjskolen i Århus Slide 4 of 38 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 Ingeniørhøjskolen i Århus Slide 5 of 38 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 Ingeniørhøjskolen i Århus Slide 6 of 38 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 Ingeniørhøjskolen i Århus Slide 7 of 38 Sort.html 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 6 7 8 9 10 Sorting an Array with Array Method sort 11 12 13 <!-- 14 function start() 15 { 16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 17 18 document.writeln( " Sorting an Array " ); 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( " " + header + 28 theArray.join( " " ) + " " ); 29 } 30 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.

8 Ingeniørhøjskolen i Århus Slide 8 of 38 Sort.html Prandram Output 31 // comparison function for use with sort 32 function compareIntegers( value1, value2 ) 33 { 34 return parseInt( value1 ) - parseInt( value2 ); 35 } 36 // --> 37 38 39 40

9 Ingeniørhøjskolen i Århus Slide 9 of 38 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 Ingeniørhøjskolen i Århus Slide 10 of 38 LinearSearch.html 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 6 7 8 9 10 Linear Search of an Array 11 12 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 } Array a 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 Array a and the value of variable searchKey as an integer.

11 Ingeniørhøjskolen i Århus Slide 11 of 38 LinearSearch.html 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 48 49 50 51 52 53 Enter integer search key 54 55 <input name = "search" type = "button" value = "Search" 56 onclick = "buttonPressed()" /> 57 58 Result 59 60 61 62 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.

12 Ingeniørhøjskolen i Århus Slide 12 of 38 Prandram Output

13 Ingeniørhøjskolen i Århus Slide 13 of 38 BinarySearch.html Study on your own 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 5 6 7 8 9 10 Binary Search 11 12 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 Array a is initiated with 15 elements.Function binarySearch receives two arguments: the Array a and the search key, searchKey.

14 Ingeniørhøjskolen i Århus Slide 14 of 38 BinarySearch.html Study on your own 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 else if ( 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 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.

15 Ingeniørhøjskolen i Århus Slide 15 of 38 BinarySearch.html Study on your own 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 high ) 74 searchForm.result.value += " "; 75 // mark middle element in output 76 else if ( 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 88 89 90 91 92 Enter integer search key 93 94 <input name = "search" type = "button" value = 95 "Search" onclick = "buttonPressed()" /> 96 Result 97 98 99 100 101 Function buildOutput creates the markup that displays the results of the search.

16 Ingeniørhøjskolen i Århus Slide 16 of 38 Prandram Output

17 Ingeniørhøjskolen i Århus Slide 17 of 38 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 Ingeniørhøjskolen i Århus Slide 18 of 38 Implicit Build-in Objects Browsers implicit objects –Array –String –Date –Function –Global (incl parseInt) –Math –Number –RegExp

19 Ingeniørhøjskolen i Århus Slide 19 of 38 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 –Shifting leaders

20 Ingeniørhøjskolen i Århus Slide 20 of 38 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 Ingeniørhøjskolen i Århus Slide 21 of 38 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 Ingeniørhøjskolen i Århus Slide 22 of 38 Examples using a String object String manipulation Searching HTML formatting Many fold of usages …

23 Ingeniørhøjskolen i Århus Slide 23 of 38 CharacterProcess ing.html 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 6 7 8 9 10 Character Processing Methods 11 12 13 <!-- 14 var s = "ZEBRA"; 15 var s2 = "AbCdEfG"; 16 17 document.writeln( " Character at index 0 in '" + 18 s + "' is " + s.charAt( 0 ) ); 19 document.writeln( " Character code at index 0 in '" 20 + s + "' is " + s.charCodeAt( 0 ) + " " ); 21 22 document.writeln( " '" + 23 String.fromCharCode( 87, 79, 82, 68 ) + 24 "' contains character codes 87, 79, 82 and 68 " ) 25 26 document.writeln( " '" + s2 + "' in lowercase is '" + 27 s2.toLowerCase() + "'" ); 28 document.writeln( " '" + s2 + "' in uppercase is '" 29 + s2.toUpperCase() + "' " ); 30 // --> 31 32 33 34 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.

24 Ingeniørhøjskolen i Århus Slide 24 of 38 Prandram Output

25 Ingeniørhøjskolen i Århus Slide 25 of 38 SearchingStrings. html 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 6 7 8 9 10 11 Searching Strings with indexOf and lastIndexOf 12 13 14 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 32 33 Method indexOf determines the first occurrence in the string letters of the string searchForm.inputVal.value. Method lastIndexOf determines the location of the last occurrence in letters of the string in text field inputVal.

26 Ingeniørhøjskolen i Århus Slide 26 of 38 SearchingStrings. html 34 35 36 The string to search is: 37 abcdefghijklmnopqrstuvwxyzabcdefghijklm 38 Enter substring to search for 39 40 <input name = "search" type = "button" value = "Search" 41 onclick = "buttonPressed()" /> 42 43 First occurrence located at index 44 45 Last occurrence located at index 46 47 First occurrence from index 12 located at index 48 49 Last occurrence from index 12 located at index 50 51 52 53

27 Ingeniørhøjskolen i Århus Slide 27 of 38 Prandram Output

28 Ingeniørhøjskolen i Århus Slide 28 of 38 MarkupMethods. html 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 6 7 8 9 10 XHTML Markup Methods of the String Object 11 12 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( " " + blinkText.blink() ); 24 document.writeln( " " + fixedText.fixed() ); 25 document.writeln( " " + strikeText.strike() ); 26 document.writeln( 27 " This is text with a " + subText.sub() ); 28 document.writeln( 29 " This is text with a " + supText.sup() ); 30 document.writeln( 31 " " + linkText.link( "#top" ) ); 32 // -->

29 Ingeniørhøjskolen i Århus Slide 29 of 38 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 Ingeniørhøjskolen i Århus Slide 30 of 38 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 Ingeniørhøjskolen i Århus Slide 31 of 38 DateTime.html 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 6 7 8 9 10 Date and Time Methods 11 12 13 <!-- 14 var current = new Date(); 15 16 document.writeln( 17 " String representations and valueOf " ); 18 document.writeln( "toString: " + current.toString() + 19 " toLocaleString: " + current.toLocaleString() + 20 " toUTCString: " + current.toUTCString() + 21 " valueOf: " + current.valueOf() ); 22 23 document.writeln( 24 " Get methods for local time zone " ); 25 document.writeln( "getDate: " + current.getDate() + 26 " getDay: " + current.getDay() + 27 " getMonth: " + current.getMonth() + 28 " getFullYear: " + current.getFullYear() + 29 " getTime: " + current.getTime() + 30 " getHours: " + current.getHours() + 31 " getMinutes: " + current.getMinutes() + 32 " getSeconds: " + current.getSeconds() + 33 " getMilliseconds: " +

32 Ingeniørhøjskolen i Århus Slide 32 of 38 DateTime.html 34 current.getMilliseconds() + 35 " getTimezoneOffset: " + 36 current.getTimezoneOffset() ); 37 38 document.writeln( 39 " Specifying arguments for a new Date " ); 40 var anotherDate = new Date( 2001, 2, 18, 1, 5, 0, 0 ); 41 document.writeln( "Date: " + anotherDate ); 42 43 document.writeln( 44 " Set methods for local time zone " ); 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 54 55 56

33 Ingeniørhøjskolen i Århus Slide 33 of 38 Prandram Output

34 Ingeniørhøjskolen i Århus Slide 34 of 38 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 Ingeniørhøjskolen i Århus Slide 35 of 38 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 Ingeniørhøjskolen i Århus Slide 36 of 38 A Sample of RegExp in JavaScript 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") } 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 Ingeniørhøjskolen i Århus Slide 37 of 38 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 Gives you the reference to the form element

38 Ingeniørhøjskolen i Århus Slide 38 of 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


Download ppt "Presentation 8: JavaScript continued Arrays and objects Internet Technology 1."

Similar presentations


Ads by Google