Presentation is loading. Please wait.

Presentation is loading. Please wait.

INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 6: Introduction to Javascript II r Javascript Objects Array String Date Math.

Similar presentations


Presentation on theme: "INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 6: Introduction to Javascript II r Javascript Objects Array String Date Math."— Presentation transcript:

1 INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 6: Introduction to Javascript II r Javascript Objects Array String Date Math Boolean

2 INE1020: Introduction to Internet Engineering 3: Web Page Authoring2 2.5. JavaScript Objects r JavaScript - object-based programming language r Objects m describe a person, place or thing m contains properties, methods and event handlers Property – describes an attribute of an object (eg, string objects have a length property) Method – an operation associated with an object (eg, write() is a method) Event handler – responds to actions (eg, mouse click is an action or event) m Encapsulate data and methods m Communicate with programs through interfaces

3 INE1020: Introduction to Internet Engineering 3: Web Page Authoring3 2.5 JavaScript Objects r JavaScript uses objects to m Interact with elements (or objects) of an HTML document window object –Enables script to manipulate browser window –window.prompt –window.alert document object –Provides access to every element of an HTML document

4 INE1020: Introduction to Internet Engineering 3: Web Page Authoring4 2.5.1 Array Object r Arrays m Data structures consisting of related data items (collections of data items) r To refer to particular element in array, specify m The name of the array m The position number of the particular element in the array  Example (to identify the 5 th element in array c ): c[4] r Position number in brackets called a subscript (or index) m If program uses an expression as a subscript, expression is evaluated first to determine the subscript

5 INE1020: Introduction to Internet Engineering 3: Web Page Authoring5 2.5.1 Array Object r First element in every array is the zeroth (0 th ) element  Therefore, element n will have a subscript value of ( n-1 )  Length of an Array determined by the expression arrayName.length Name of array (Note that all elements of this array have the same name, c ) Position number of the element within array c c[6] c[0] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] 45 6 0 72 1543 - 89 0 62 - 3 1 4563 78 c[1]

6 INE1020: Introduction to Internet Engineering 3: Web Page Authoring6 2.5.1 Array Object  An array in JavaScript is an Array object r JavaScript arrays are dynamic entities m Can change size after being created  Operator new creates an object as the program executes m Obtains enough memory to store an object of the type specified r Process of creating objects also known as m Creating an instance or m Instantiating an object  new m Dynamic memory allocation operator

7 INE1020: Introduction to Internet Engineering 3: Web Page Authoring7 2.5.1 Array Object  To allocate 12 elements for integer array c var c = new Array( 12 ); m Reserves 12 elements for array c m When arrays allocated, elements not initialized r Arrays can also be initialized with no elements m Grow dynamically to accommodate new elements var d = new Array();  Initializes empty array d  Element values can be printed using the regular writeln method document.writeln( “ The value is “ + d[2] );

8 INE1020: Introduction to Internet Engineering 3: Web Page Authoring8 2.5.1 Array Object r The elements of an Array can be allocated and initialized in the array declaration r This can be done in two ways  To initialize array n with five known elements: var n = [ 10, 20, 30, 40, 50 ]; or var n = new Array( 10, 20, 30, 40, 50 ); m Uses a comma-separated initializer list enclosed in square brackets  To reserve a space in an Array for an unspecified value m Use a comma as a place holder in the initializer list var n = [ 10, 20,, 40, 50 ];  Creates five element array with no value specified for n[2]  n[2] will appear undefined until it is initialized

9 INE1020: Introduction to Internet Engineering 3: Web Page Authoring9 2.5.1 Array Object Histogram Printing Program function start() { var theArray = [ 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 ]; document.writeln( " " ); document.writeln( " Element " + " Value " + " Histogram " ); for ( var i in theArray ) { document.writeln( " " + i + " " + theArray[ i ] + " " ); // print a bar of asteriks for ( var j = 1; j <= theArray[ i ]; ++j ) document.writeln( "*" ); document.writeln( " " ); } document.writeln( " " ); }

10 INE1020: Introduction to Internet Engineering 3: Web Page Authoring10 2.5.1 Array Object r Script output: Printing a histogram

11 INE1020: Introduction to Internet Engineering 3: Web Page Authoring11 2.5.1 Sorting Arrays r Sorting data is one of most important computing scripts m Virtually every organization must sort data in some amount  Array object in JavaScript has built-in function sort m No arguments Uses string comparisons to determine sorting order m With optional arguments Takes the name of a function called the comparator function Comparator function takes two arguments and returns –A negative value if the first argument is less than the second –Zero if the arguments are equal –A positive value if the first argument is greater than the second

12 INE1020: Introduction to Internet Engineering 3: Web Page Authoring12 2.5.1 Sorting Arrays Sorting an Array with Array Method sort function start() { var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; document.writeln( " Sorting an Array " ); outputArray( "Data items in original order: ", a ); a.sort( compareIntegers ); // sort the array outputArray( "Data items in ascending order: ", a ); } // outputs "header" followed by the contents of "theArray" function outputArray( header, theArray ) { document.writeln( " " + header + theArray.join( " " ) + " " ); } // comparison function for use with sort function compareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); }

13 INE1020: Introduction to Internet Engineering 3: Web Page Authoring13 2.5.1 Sorting Arrays r CompareIntegers function is used as comparator function for method sort. m It calculates the difference between the integers values of its 2 arguments using parseInt m parseInt function ensures that the arguments are handled properly as integers r Script output:

14 INE1020: Introduction to Internet Engineering 3: Web Page Authoring14 2.5.1 Searching Arrays: Linear Search r When working with large amounts of data m May be necessary to determine whether an array contains a value that matches a certain key value m Searching – process of locating particular element value in an array r Linear searching m Compares each element in an array with a search key m Goes in order of elements in array If array unsorted, just as likely value will be found in first element as the last element m Works well for small arrays or unsorted arrays m Inefficient for large arrays

15 INE1020: Introduction to Internet Engineering 3: Web Page Authoring15 2.5.1 Searching Arrays: Linear Search r Example of searching an array for an integer number Linear Search of an Array var a = new Array( 100 ); // create an Array // fill Array with even integer values from 0 to 198 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i; // function called when "Search" button is pressed function buttonPressed() { var searchKey = searchForm.inputVal.value; // Array a is passed to linearSearch even though it // is a global variable. Normally an array will // be passed to a method for searching. var element = linearSearch( a, parseInt( searchKey ) ); if ( element != -1 ) searchForm.result.value = "Found value in element " + element; else searchForm.result.value = "Value not found"; }

16 INE1020: Introduction to Internet Engineering 3: Web Page Authoring16 2.5.1 Searching Arrays: Linear Search // Search "theArray" for the specified "key" value function linearSearch( theArray, key ) { for ( var n = 0; n < theArray.length; ++n ) if ( theArray[ n ] == key ) return n; return -1; //If serach key is NOT found, linearSearch returns -1 // -1 is used because it is NOT a valid subscript number } Enter integer search key <INPUT NAME = "search" TYPE = "button" VALUE = "Search" ONCLICK = "buttonPressed()"> Result

17 INE1020: Introduction to Internet Engineering 3: Web Page Authoring17 2.5.1 Searching Arrays: Linear Search r The array is filled with even number between 0 to 198. r Script output:

18 INE1020: Introduction to Internet Engineering 3: Web Page Authoring18 2.5.1 Multiple-Subscripted Arrays r Multiple-Subscripted Arrays with two subscripts m Often represent tables of values consisting of info arranged in rows and columns r Double-subscripted array (or two-dimensional arrays) m Require two subscripts to identify a particular element First subscript identifies element’s row Second subscript identifies element’s column r m-by-n array m An array with m rows and n columns

19 INE1020: Introduction to Internet Engineering 3: Web Page Authoring19 2.5.1 Multiple-Subscripted Arrays r Double-scripted array with three rows and four columns a[0][0]a[0][1] a[1][0]a[1][1] a[2][0]a a[0][2] a[1][2] a[0][3] a[1][3] a[2][2]a[2][3][2][1] Column 3Column 0Column 2Column 1 Row 0 Row 1 Row 2 Column subscript Row subscript Array name

20 INE1020: Introduction to Internet Engineering 3: Web Page Authoring20 2.5.1 Multiple-Subscripted Arrays r Initialization m Declared like a single-scripted array  Double scripted array b with two rows and two columns could be declared and initialized with var b = [ [ 1, 2 ], [ 3, 4 ] ]; m Compiler determines number of elements in row/column By counting number of initializer values in sub-initializer list for that row/column r Can have a different number of columns in each row  eg, var b = [ [ 1, 2 ], [ 3, 4, 5 ] ]; m array b has row 1 containing elements (1 and 2) & row 1 containing 3 elements (3, 4, 5) r for and for/in loops used to traverse the arrays m Manipulate every element of the array

21 INE1020: Introduction to Internet Engineering 3: Web Page Authoring21 2.5.1 Multiple-Subscripted Arrays Initializing Multidimensional Arrays function start() { var array1 = [ [ 1, 2, 3 ], // first row [ 4, 5, 6 ] ]; // second row var array2 = [ [ 1, 2 ], // first row [ 3 ], // second row [ 4, 5, 6 ] ]; // third row outputArray( "Values in array1 by row", array1 ); outputArray( "Values in array2 by row", array2 ); } function outputArray( header, theArray ) { document.writeln( " " + header + " " ); for ( var i in theArray ) { for ( var j in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); document.writeln( " " ); } document.writeln( " " ); }

22 INE1020: Introduction to Internet Engineering 3: Web Page Authoring22 2.5.1 Multiple-Subscripted Arrays r The script uses nested for/in structures to traverse the arrays and output their contents r Script output:

23 INE1020: Introduction to Internet Engineering 3: Web Page Authoring23 2.5.2. String Object r String Object m JavaScript’s string and character processing capabilities r Appropriate for developing m Text editors m Word processors m Page layout software m Computerized typesetting systems m Other kinds of text-processing software

24 INE1020: Introduction to Internet Engineering 3: Web Page Authoring24 2.5.2. String Object r Fundamentals of Characters and Strings m Characters Fundamental building blocks of JavaScript programs m String Series of Characters treated as a single unit May include –Letters –Digits –Special Characters +, _, /, $, etc.

25 INE1020: Introduction to Internet Engineering 3: Web Page Authoring25 2.5.2. String Object r String literals / string constant m Written as sequence of characters in single or double quotation marks r Strings may be assigned to variables in declarations var color = “ blue ” ; r Strings may be compared with m Relational operators m Equality operators

26 INE1020: Introduction to Internet Engineering 3: Web Page Authoring26 2.5.2. String Object r String object m Encapsulates the attributes and behaviors of a string of characters r Format for calling methods (except in certain cases) stringName.methodName( ); r Provides methods for m Selecting characters from a string m Combining strings (concatenation) m Obtaining substrings of a string m Searching for substrings within a string m Tokenizing a string m Converting strings to all uppercase or lowercase m Generate HTML tags

27 INE1020: Introduction to Internet Engineering 3: Web Page Authoring27 2.5.2. String Object

28 INE1020: Introduction to Internet Engineering 3: Web Page Authoring28 2.5.2. String Object

29 INE1020: Introduction to Internet Engineering 3: Web Page Authoring29 2.5.2. Split String: Example String Method split and substring function splitButtonPressed() { var strings = myForm.inputVal.value.split( " " ); myForm.output.value = strings.join( "\n" ); myForm.outputSubstring.value = myForm.inputVal.value.substring( 0, 10 ); }

30 INE1020: Introduction to Internet Engineering 3: Web Page Authoring30 2.5.2. Split String: Example Enter a sentence to split into words <input name = "splitButton" type = "button" value = "Split" onclick = "splitButtonPressed()" /> The sentence split into words is The first 10 characters of the input string are <input name = "outputSubstring" type = "text" size = "15" />

31 INE1020: Introduction to Internet Engineering 3: Web Page Authoring31 2.5.2. Split String: Example

32 INE1020: Introduction to Internet Engineering 3: Web Page Authoring32 2.5.2. String Object r HTML Markup Methods of String Object

33 INE1020: Introduction to Internet Engineering 3: Web Page Authoring33 2.5.3. Date Object  JavaScript’s Date object m Provides methods for date and time manipulation r Date and time processing can be performed based on m Local time zone m Universal Coordinated Time (UTC) / Greenwich Mean Time (GMT)  Most methods in Date object have local time zone and UTC versions  When using Date object  Initialize Date object with current date and time var current = new Date(); Allocates memory for object, calls Date object constructor –Constructor is an initializer method for an object

34 INE1020: Introduction to Internet Engineering 3: Web Page Authoring34 2.5.3. Date Object  New Date object creation new Date( year, month, date, hours, minutes, seconds, milliseconds ); Hours, minutes, seconds and milliseconds are optional If argument to the right is specified, all arguments to the left must also be specified Month represented internally as integers from 0-11 –Therefore, March is indicated by 2, November by 10, etc. Write out years in 4-digit form (i.e. ‘2000’, not ’00’) –Avoid potential Y2K problems

35 INE1020: Introduction to Internet Engineering 3: Web Page Authoring35 2.5.4. Math Object r Math object’s methods m Allow programmer to perform many common mathematical calculations r Properties of the Math object

36 INE1020: Introduction to Internet Engineering 3: Web Page Authoring36 2.5.4. Math Object r Commonly Used Math Object Methods

37 INE1020: Introduction to Internet Engineering 3: Web Page Authoring37 2.5.4. Math Object  Commonly used Math object methods

38 INE1020: Introduction to Internet Engineering 3: Web Page Authoring38 2.5.5. Boolean and Number Objects  Boolean and Number objects m Provided as object wrappers for Boolean true/false values Numbers m Wrappers define methods and properties useful in manipulating boolean values and numbers r Number object  JavaScript automatically creates Number objects to store numeric values  Programmers can create a Number object with var n = new Number( numericValue );

39 INE1020: Introduction to Internet Engineering 3: Web Page Authoring39 2.5.5. Boolean and Number Objects  Boolean object  When boolean value required in a program, automatically created by JavaScript to store the value using Boolean object  Programmers can create Boolean objects explicitly var b = new Boolean( booleanValue );  If booleanvalue equals false, 0, null, Number.NaN or empty string (“ ”) Boolean object contains false m Otherwise Boolean Object contains true

40 INE1020: Introduction to Internet Engineering 3: Web Page Authoring40 Further Readings r Note: This topic is designed with the objective of providing an introduction to Javascript Array and Objects. r Advanced features of Javascript Array and Objects are beyond the scope of this course and will NOT be taught or discussed. Students who wish to invest more time on studying advanced features and topics of Javascript are referred to the following resources: m Deitel Chapter 11-12 m http://developer.netscape.com/docs/manuals/javascript.html http://developer.netscape.com/docs/manuals/javascript.html


Download ppt "INE1020: Introduction to Internet Engineering 3: Web Page Authoring1 Lecture 6: Introduction to Javascript II r Javascript Objects Array String Date Math."

Similar presentations


Ads by Google