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

Slides:



Advertisements
Similar presentations
Números.
Advertisements

1 A B C
JavaScript: Functions
Trend for Precision Soil Testing % Zone or Grid Samples Tested compared to Total Samples.
Trend for Precision Soil Testing % Zone or Grid Samples Tested compared to Total Samples.
AGVISE Laboratories %Zone or Grid Samples – Northwood laboratory
Trend for Precision Soil Testing % Zone or Grid Samples Tested compared to Total Samples.
Simplifications of Context-Free Grammars
PDAs Accept Context-Free Languages
AP STUDY SESSION 2.
1
EuroCondens SGB E.
Worksheets.
Copyright © 2003 Pearson Education, Inc. Slide 7-1 Created by Cheryl M. Hughes The Web Wizards Guide to XML by Cheryl M. Hughes.
Addition and Subtraction Equations
David Burdett May 11, 2004 Package Binding for WS CDL.
Create an Application Title 1Y - Youth Chapter 5.
Add Governors Discretionary (1G) Grants Chapter 6.
CALENDAR.
The 5S numbers game..
突破信息检索壁垒 -SciFinder Scholar 介绍
A Fractional Order (Proportional and Derivative) Motion Controller Design for A Class of Second-order Systems Center for Self-Organizing Intelligent.
Media-Monitoring Final Report April - May 2010 News.
Break Time Remaining 10:00.
The basics for simulations
Factoring Quadratics — ax² + bx + c Topic
Turing Machines.
Anything But Typical Learning to Love JavaScript Prototypes Page 1 © 2010 Razorfish. All rights reserved. Dan Nichols March 14, 2010.
PP Test Review Sections 6-1 to 6-6
MM4A6c: Apply the law of sines and the law of cosines.
Briana B. Morrison Adapted from William Collins
Figure 3–1 Standard logic symbols for the inverter (ANSI/IEEE Std
2000 Deitel & Associates, Inc. All rights reserved. Chapter 16 – Bits, Characters, Strings, and Structures Outline 16.1Introduction 16.2Structure Definitions.
Operating Systems Operating Systems - Winter 2010 Chapter 3 – Input/Output Vrije Universiteit Amsterdam.
Dynamic Access Control the file server, reimagined Presented by Mark on twitter 1 contents copyright 2013 Mark Minasi.
Copyright © 2012, Elsevier Inc. All rights Reserved. 1 Chapter 7 Modeling Structure with Blocks.
Progressive Aerobic Cardiovascular Endurance Run
Adding Up In Chunks.
MaK_Full ahead loaded 1 Alarm Page Directory (F11)
1 Termination and shape-shifting heaps Byron Cook Microsoft Research, Cambridge Joint work with Josh Berdine, Dino Distefano, and.
Artificial Intelligence
When you see… Find the zeros You think….
2011 WINNISQUAM COMMUNITY SURVEY YOUTH RISK BEHAVIOR GRADES 9-12 STUDENTS=1021.
Before Between After.
2011 FRANKLIN COMMUNITY SURVEY YOUTH RISK BEHAVIOR GRADES 9-12 STUDENTS=332.
Subtraction: Adding UP
: 3 00.
5 minutes.
1 Non Deterministic Automata. 2 Alphabet = Nondeterministic Finite Accepter (NFA)
1 hi at no doifpi me be go we of at be do go hi if me no of pi we Inorder Traversal Inorder traversal. n Visit the left subtree. n Visit the node. n Visit.
Types of selection structures
1 Titre de la diapositive SDMO Industries – Training Département MICS KERYS 09- MICS KERYS – WEBSITE.
Static Equilibrium; Elasticity and Fracture
Converting a Fraction to %
Numerical Analysis 1 EE, NCKU Tien-Hao Chang (Darby Chang)
Resistência dos Materiais, 5ª ed.
CSE20 Lecture 15 Karnaugh Maps Professor CK Cheng CSE Dept. UC San Diego 1.
Clock will move after 1 minute
 2002 Prentice Hall. All rights reserved. 1 Chapter 15 – Strings, Characters and Regular Expressions Outline 15.1Introduction 15.2 Fundamentals of Characters.
Lial/Hungerford/Holcomb/Mullins: Mathematics with Applications 11e Finite Mathematics with Applications 11e Copyright ©2015 Pearson Education, Inc. All.
Physics for Scientists & Engineers, 3rd Edition
Select a time to count down from the clock above
Copyright Tim Morris/St Stephen's School
1.step PMIT start + initial project data input Concept Concept.
1 Dr. Scott Schaefer Least Squares Curves, Rational Representations, Splines and Continuity.
Introduction Embedded Universal Tools and Online Features 2.
Schutzvermerk nach DIN 34 beachten 05/04/15 Seite 1 Training EPAM and CANopen Basic Solution: Password * * Level 1 Level 2 * Level 3 Password2 IP-Adr.
Presentation transcript:

Presentation 8: JavaScript continued Arrays and objects Internet Technology 1

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.

Ingeniørhøjskolen i Århus Slide 3 of 38 Array of data c[ 6 ] 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!!

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)

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]

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:

Ingeniørhøjskolen i Århus Slide 7 of 38 Sort.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Sorting an Array with Array Method sort <!-- 14 function start() 15 { 16 var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; 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 } // 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.

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

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

Ingeniørhøjskolen i Århus Slide 10 of 38 LinearSearch.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Linear Search of an Array <!-- 14 var a = new Array( 100 ); // create an Array // fill Array with even integer values from 0 to for ( var i = 0; i < a.length; ++i ) 18 a[ i ] = 2 * i; // function called when "Search" button is pressed 21 function buttonPressed() 22 { 23 var searchKey = searchForm.inputVal.value; // 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 ) ); 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.

Ingeniørhøjskolen i Århus Slide 11 of 38 LinearSearch.html // 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; return -1; 45 } 46 // --> Enter integer search key <input name = "search" type = "button" value = "Search" 56 onclick = "buttonPressed()" /> Result 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 Århus Slide 12 of 38 Prandram Output

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 " Binary Search <!-- 14 var a = new Array( 15 ); for ( var i = 0; i < a.length; ++i ) 17 a[ i ] = 2 * i; // function called when "Search" button is pressed 20 function buttonPressed() 21 { 22 var searchKey = searchForm.inputVal.value; searchForm.result.value = 25 "Portions of array searched\n"; // 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.

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 } // 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 while ( low <= high ) { 49 middle = ( low + high ) / 2; // 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 ); 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 } 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.

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 } searchForm.result.value += "\n"; 85 } 86 // --> Enter integer search key <input name = "search" type = "button" value = 95 "Search" onclick = "buttonPressed()" /> 96 Result Function buildOutput creates the markup that displays the results of the search.

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

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)

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

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

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..”);

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

Ingeniørhøjskolen i Århus Slide 22 of 38 Examples using a String object String manipulation Searching HTML formatting Many fold of usages …

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 " Character Processing Methods <!-- 14 var s = "ZEBRA"; 15 var s2 = "AbCdEfG"; 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 ) + " " ); document.writeln( " '" + 23 String.fromCharCode( 87, 79, 82, 68 ) + 24 "' contains character codes 87, 79, 82 and 68 " ) document.writeln( " '" + s2 + "' in lowercase is '" + 27 s2.toLowerCase() + "'" ); 28 document.writeln( " '" + s2 + "' in uppercase is '" 29 + s2.toUpperCase() + "' " ); 30 // --> 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 Århus Slide 24 of 38 Prandram Output

Ingeniørhøjskolen i Århus Slide 25 of 38 SearchingStrings. html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Searching Strings with indexOf and lastIndexOf <!-- 16 var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm"; 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 // --> 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 Århus Slide 26 of 38 SearchingStrings. html The string to search is: 37 abcdefghijklmnopqrstuvwxyzabcdefghijklm 38 Enter substring to search for <input name = "search" type = "button" value = "Search" 41 onclick = "buttonPressed()" /> First occurrence located at index Last occurrence located at index First occurrence from index 12 located at index Last occurrence from index 12 located at index

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

Ingeniørhøjskolen i Århus Slide 28 of 38 MarkupMethods. html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " XHTML Markup Methods of the String Object <!-- 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"; 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 // -->

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

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

Ingeniørhøjskolen i Århus Slide 31 of 38 DateTime.html 1 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 3 " Date and Time Methods <!-- 14 var current = new Date(); 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() ); 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: " +

Ingeniørhøjskolen i Århus Slide 32 of 38 DateTime.html 34 current.getMilliseconds() + 35 " getTimezoneOffset: " + 36 current.getTimezoneOffset() ); 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 ); 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 // -->

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

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

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 adress. Deitel do not include RegularExpressions under JavaScript –Out of Curriculum –You may look under Pyton –For a tutorial in RegularExpressions to JavaScript see:

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

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

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