410 likes | 661 Views
Lecture 6: Introduction to Javascript II. Javascript Objects Array String Date Math Boolean. 2.5. JavaScript Objects. JavaScript - object-based programming language Objects describe a person, place or thing contains properties, methods and event handlers
E N D
Lecture 6: Introduction to Javascript II • Javascript Objects • Array • String • Date • Math • Boolean 3: Web Page Authoring
2.5. JavaScript Objects • JavaScript - object-based programming language • Objects • describe a person, place or thing • 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) • Encapsulate data and methods • Communicate with programs through interfaces 3: Web Page Authoring
2.5 JavaScript Objects • JavaScript uses objects to • 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 3: Web Page Authoring
2.5.1 Array Object • Arrays • Data structures consisting of related data items (collections of data items) • To refer to particular element in array, specify • The name of the array • The position number of the particular element in the array • Example (to identify the 5th element in array c): c[4] • Positionnumberinbracketscalled a subscript (or index) • If program uses an expression as a subscript, expression is evaluated first to determine the subscript 3: Web Page Authoring
First element in every array is the zeroth (0th) 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 allelements of this array have thesame name, c) c[0] 45 6 c[1] 0 c[2] 72 1543 c[3] - 89 c[4] 0 62 c[5] - 3 c[6] 1 4563 c[7] 78 c[8] c[9] c[10] c[11] Position number of the elementwithin array c 2.5.1 Array Object 3: Web Page Authoring
2.5.1 Array Object • An array in JavaScript is an Arrayobject • JavaScript arrays are dynamic entities • Can change size after being created • Operator new creates an object as the program executes • Obtains enough memory to store an object of the type specified • Process of creating objects also known as • Creating an instance or • Instantiating an object • new • Dynamic memory allocation operator 3: Web Page Authoring
2.5.1 Array Object • To allocate 12 elements for integer array c var c = new Array( 12 ); • Reserves 12 elements for array c • When arrays allocated, elements not initialized • Arrays can also be initialized with no elements • 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] ); 3: Web Page Authoring
2.5.1 Array Object • The elements of an Array can be allocated and initialized in the array declaration • 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 ); • Usesacomma-separatedinitializerlistenclosedinsquarebrackets • To reserve a space in an Array for an unspecified value • 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 3: Web Page Authoring
2.5.1 Array Object <HTML> <HEAD> <TITLE> Histogram Printing Program</TITLE> <SCRIPT LANGUAGE ="JavaScript"> function start() { var theArray = [ 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 ]; document.writeln( "<TABLE BORDER = '1' WIDTH = '100%'>" ); document.writeln( "<TR><TD WIDTH = '100'><B>Element</B>" + "<TD WIDTH = '100'><B>Value</B>" + "<TD><B>Histogram</B></TR>" ); for ( var i in theArray ) { document.writeln( "<TR><TD>" + i + "<TD>" + theArray[ i ] + "<TD>" ); // print a bar of asteriks for ( var j = 1; j <= theArray[ i ]; ++j ) document.writeln( "*" ); document.writeln( "</TR>" ); } document.writeln( "</TABLE>" ); } </SCRIPT> </HEAD> <BODY ONLOAD = "start()"></BODY> </HTML> 3: Web Page Authoring
2.5.1 Array Object • Script output: Printing a histogram 3: Web Page Authoring
2.5.1 Sorting Arrays • Sorting data is one of most important computing scripts • Virtually every organization must sort data in some amount • Array object in JavaScript has built-in function sort • No arguments • Uses string comparisons to determine sorting order • 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 3: Web Page Authoring
2.5.1 Sorting Arrays <HTML> <HEAD> <TITLE> Sorting an Array with Array Method sort </TITLE> <SCRIPT LANGUAGE ="JavaScript"> function start() { var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; document.writeln( "<H1>Sorting an Array</H1>" ); 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( "<P>" + header + theArray.join( " " ) + "</P>" ); } // comparison function for use with sort functioncompareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); } </SCRIPT> </HEAD> <BODY ONLOAD = "start()"></BODY> </HTML> 3: Web Page Authoring
2.5.1 Sorting Arrays • CompareIntegers function is used as comparator function for method sort. • It calculates the difference between the integers values of its 2 arguments using parseInt • parseInt function ensures that the arguments are handled properly as integers • Script output: 3: Web Page Authoring
2.5.1 Searching Arrays: Linear Search • When working with large amounts of data • May be necessary to determine whether an array contains a value that matches a certain key value • Searching – process of locating particular element value in an array • Linear searching • Compares each element in an array with a search key • Goes in order of elements in array • If array unsorted, just as likely value will be found in first element as the last element • Works well for small arrays or unsorted arrays • Inefficient for large arrays 3: Web Page Authoring
2.5.1 Searching Arrays: Linear Search • Example of searching an array for an integer number <HTML> <HEAD> <TITLE> Linear Search of an Array</TITLE> <SCRIPT LANGUAGE ="JavaScript"> 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"; } 3: Web Page Authoring
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 } </SCRIPT> </HEAD> <BODY> <FORM NAME = "searchForm"> <P>Enter integer search key<BR> <INPUT NAME ="inputVal"TYPE ="text"> <INPUT NAME ="search"TYPE ="button"VALUE ="Search" ONCLICK ="buttonPressed()"><BR></P> <P>Result<BR> <INPUT NAME ="result"TYPE ="text"SIZE ="30"></P> </FORM> </BODY> </HTML> 3: Web Page Authoring
2.5.1 Searching Arrays: Linear Search • The array is filled with even number between 0 to 198. • Script output: 3: Web Page Authoring
2.5.1 Multiple-Subscripted Arrays • Multiple-Subscripted Arrays with two subscripts • Often represent tables of values consisting of info arranged in rows and columns • Double-subscripted array (or two-dimensional arrays) • Require two subscripts to identify a particular element • First subscript identifies element’s row • Second subscript identifies element’s column • m-by-n array • An array with m rows and n columns 3: Web Page Authoring
Column 0 Column 1 Column 2 Column 3 Row 0 a[0][0] a[0][1] a[0][2] a[0][3] Row 1 a[1][0] a[1][1] a[1][2] a[1][3] Row 2 a[2][0] a [2] [1] a[2][2] a[2][3] Column subscript Row subscript Array name 2.5.1 Multiple-Subscripted Arrays • Double-scripted array with three rows and four columns 3: Web Page Authoring
2.5.1 Multiple-Subscripted Arrays • Initialization • 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 ] ]; • Compiler determines number of elements in row/column • By counting number of initializer values in sub-initializer list for that row/column • Can have a different number of columns in each row • eg, var b = [ [ 1, 2 ], [ 3, 4, 5 ] ]; • array b has row 1 containing elements (1 and 2) & row 1 containing 3 elements (3, 4, 5) • for and for/in loops used to traverse the arrays • Manipulate every element of the array 3: Web Page Authoring
2.5.1 Multiple-Subscripted Arrays <HTML> <HEAD> <TITLE> Initializing Multidimensional Arrays</TITLE> <SCRIPT LANGUAGE ="JavaScript"> 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( "<H2>" + header + "</H2><TT>" ); for ( var i in theArray ) { for ( var j in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); document.writeln( "<BR>" ); } document.writeln( "</TT>" ); } </SCRIPT> </HEAD> <BODY ONLOAD = "start()"></BODY> </HTML> 3: Web Page Authoring
2.5.1 Multiple-Subscripted Arrays • The script uses nested for/in structures to traverse the arrays and output their contents • Script output: 3: Web Page Authoring
2.5.2. String Object • String Object • JavaScript’s string and character processing capabilities • Appropriate for developing • Text editors • Word processors • Page layout software • Computerized typesetting systems • Other kinds of text-processing software 3: Web Page Authoring
2.5.2. String Object • Fundamentals of Characters and Strings • Characters • Fundamental building blocks of JavaScript programs • String • Series of Characters treated as a single unit • May include • Letters • Digits • Special Characters +, _, /, $, etc. 3: Web Page Authoring
2.5.2. String Object • String literals / string constant • Written as sequence of characters in single or double quotation marks • Strings may be assigned to variables in declarations var color = “blue”; • Strings may be compared with • Relational operators • Equality operators 3: Web Page Authoring
2.5.2. String Object • String object • Encapsulates the attributes and behaviors of a string of characters • Format for calling methods (except in certain cases) stringName.methodName( ); • Provides methods for • Selecting characters from a string • Combining strings (concatenation) • Obtaining substrings of a string • Searching for substrings within a string • Tokenizing a string • Converting strings to all uppercase or lowercase • Generate HTML tags 3: Web Page Authoring
2.5.2. String Object 3: Web Page Authoring
2.5.2. String Object 3: Web Page Authoring
2.5.2. Split String: Example <html> <head> <title>String Method split and substring</title> <script type = "text/javascript"> function splitButtonPressed() { var strings = myForm.inputVal.value.split( " " ); myForm.output.value = strings.join( "\n" ); myForm.outputSubstring.value = myForm.inputVal.value.substring( 0, 10 ); } </script> </head> 3: Web Page Authoring
2.5.2. Split String: Example <body> <form name = "myForm" action = ""> <p>Enter a sentence to split into words<br /> <input name = "inputVal" type = "text" size = "40" /> <input name = "splitButton" type = "button" value = "Split" onclick = "splitButtonPressed()" /></p> <p>The sentence split into words is<br /> <textarea name = "output" rows = "8" cols = "34"> </textarea></p> <p>The first 10 characters of the input string are <input name = "outputSubstring" type = "text" size = "15" /></p> </form> </body> </html> 3: Web Page Authoring
2.5.2. Split String: Example 3: Web Page Authoring
2.5.2. String Object • HTML Markup Methods of String Object 3: Web Page Authoring
2.5.3. Date Object • JavaScript’s Date object • Provides methods for date and time manipulation • Date and time processing can be performed based on • Local time zone • 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 3: Web Page Authoring
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 3: Web Page Authoring
2.5.4. Math Object • Math object’s methods • Allow programmer to perform many common mathematical calculations • Properties of the Math object 3: Web Page Authoring
2.5.4. Math Object • Commonly Used Math Object Methods 3: Web Page Authoring
2.5.4. Math Object • Commonly used Math object methods 3: Web Page Authoring
2.5.5. Boolean and Number Objects • Boolean and Numberobjects • Provided as object wrappers for • Boolean true/false values • Numbers • Wrappers define methods and properties useful in manipulating boolean values and numbers • Number object • JavaScript automatically creates Number objects to store numeric values • Programmers can create a Number object with var n = new Number( numericValue ); 3: Web Page Authoring
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 • Otherwise • Boolean Object contains true 3: Web Page Authoring
Further Readings • Note: This topic is designed with the objective of providing an introduction toJavascript Array and Objects. • 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: • Deitel Chapter 11-12 • http://developer.netscape.com/docs/manuals/javascript.html 3: Web Page Authoring