presentation 8: javascript continued arrays and objects internet technology 1

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

Upload: jaliyah-bane

Post on 11-Dec-2015

233 views

Category:

Documents


0 download

TRANSCRIPT

Presentation 8:

JavaScript continued

Arrays and objects

Internet Technology 1

Ingeniørhøjskolen i ÅrhusSlide 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.

Ingeniørhøjskolen i ÅrhusSlide 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) ofa element in the array

Fig. 11.1 A 12-element array.

AN ARRAY ARE ALWAYS AN

OBJECT IN A JAVASCRIPT!

- It got methods!!

Ingeniørhøjskolen i ÅrhusSlide 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)

Ingeniørhøjskolen i ÅrhusSlide 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]

Ingeniørhøjskolen i ÅrhusSlide 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:

Ingeniørhøjskolen i ÅrhusSlide 7 of 38

Sort.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.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 array21 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

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.

Ingeniørhøjskolen i ÅrhusSlide 8 of 38

Sort.html

Prandram Output

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

Ingeniørhøjskolen i ÅrhusSlide 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

Ingeniørhøjskolen i ÅrhusSlide 10 of 38

LinearSearch.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.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 Array15 16 // fill Array with even integer values from 0 to 19817 for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i;19 20 // function called when "Search" button is pressed21 function buttonPressed()22 {23 var searchKey = searchForm.inputVal.value;24 25 // Array a is passed to linearSearch even though it26 // is a global variable. Normally an array will27 // 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 else34 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.

Ingeniørhøjskolen i ÅrhusSlide 11 of 38

LinearSearch.html

36 37 // Search "theArray" for the specified "key" value38 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>

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.

Ingeniørhøjskolen i ÅrhusSlide 12 of 38

Prandram Output

Ingeniørhøjskolen i ÅrhusSlide 13 of 38

BinarySearch.htmlStudy on your own

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 pressed20 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 it28 // is a global variable. This is done because 29 // normally an array is passed to a method30 // 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.

Ingeniørhøjskolen i ÅrhusSlide 14 of 38

BinarySearch.html Study on your own

34 if ( element != -1 )35 searchForm.result.value += 36 "\nFound value in element " + element;37 else38 searchForm.result.value += "\nValue not found";39 }40 41 // Binary search42 function binarySearch( theArray, key ) 43 {44 var low = 0; // low subscript45 var high = theArray.length - 1; // high subscript46 var middle; // middle subscript47 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 ] ) // match58 return middle;59 else if ( key < theArray[ middle ] )60 high = middle - 1; // search low end of array61 else62 low = middle + 1; // search high end of array63 }64 65 return -1;// searchKey not found66 }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.

Ingeniørhøjskolen i ÅrhusSlide 15 of 38

BinarySearch.html Study on your own

68 // Build one row of output showing the current69 // 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 output76 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 </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>

Function buildOutput creates the markup that displays the results of the search.

Ingeniørhøjskolen i ÅrhusSlide 16 of 38

Prandram Output

Ingeniørhøjskolen i ÅrhusSlide 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)

Ingeniørhøjskolen i ÅrhusSlide 18 of 38

Implicit Build-in Objects

• Browsers implicit objects – Array – String – Date– Function– Global (incl parseInt)– Math – Number – RegExp

Ingeniørhøjskolen i ÅrhusSlide 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

Ingeniørhøjskolen i ÅrhusSlide 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..”);

Ingeniørhøjskolen i ÅrhusSlide 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

Ingeniørhøjskolen i ÅrhusSlide 22 of 38

Examples using a String object

• String manipulation• Searching• HTML formatting• Many fold of usages …

Ingeniørhøjskolen i ÅrhusSlide 23 of 38

CharacterProcessing.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. 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>

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.

Ingeniørhøjskolen i ÅrhusSlide 24 of 38

Prandram Output

Ingeniørhøjskolen i ÅrhusSlide 25 of 38

SearchingStrings.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. 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 lastIndexOf12 </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>

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.

Ingeniørhøjskolen i ÅrhusSlide 26 of 38

SearchingStrings.html

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 index46 <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 index50 <input name = "last12" type = "text" size = "5" /></p>51 </form>52 </body>53 </html>

Ingeniørhøjskolen i ÅrhusSlide 27 of 38

Prandram Output

Ingeniørhøjskolen i ÅrhusSlide 28 of 38

MarkupMethods.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. 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 // -->

Ingeniørhøjskolen i ÅrhusSlide 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

Ingeniørhøjskolen i ÅrhusSlide 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

Ingeniørhøjskolen i ÅrhusSlide 31 of 38

DateTime.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. 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: " +

Ingeniørhøjskolen i ÅrhusSlide 32 of 38

DateTime.html

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>

Ingeniørhøjskolen i ÅrhusSlide 33 of 38

Prandram Output

Ingeniørhøjskolen i ÅrhusSlide 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

Ingeniørhøjskolen i ÅrhusSlide 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

Ingeniørhøjskolen i ÅrhusSlide 36 of 38

A Sample of RegExp in JavaScript<script language="JavaScript1.2">

function checkpostal(){var re5digit=/^\d{5}$/ //regular expression defining a 5 digit numberif (document.myform.myinput.value.search(re5digit)==-1) //if match failedalert("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

Ingeniørhøjskolen i ÅrhusSlide 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• <input type=”text” name=”zip” onChange=”validate(this)”>• Gives you the reference to the form element

Ingeniørhøjskolen i ÅrhusSlide 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