ine1020: introduction to internet engineering 3: web page authoring1 lecture 6: introduction to...
TRANSCRIPT
3: Web Page Authoring 1INE1020: Introduction to Internet
Engineering
Lecture 6: Introduction to Javascript II
Javascript Objects• Array• String• Date• Math• Boolean
3: Web Page Authoring 2INE1020: Introduction to Internet
Engineering
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 3INE1020: Introduction to Internet
Engineering
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 4INE1020: Introduction to Internet
Engineering
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]
Position number in brackets called a subscript (or index) If program uses an expression as a subscript,
expression is evaluated first to determine the subscript
3: Web Page Authoring 5INE1020: Introduction to Internet
Engineering
2.5.1 Array Object
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 expressionarrayName.length
Name of array (Note that allelements of this array have thesame name, c)
Position number of the elementwithin array c
c[6]
c[0]
c[2]
c[3]
c[11]
c[10]c[9]c[8]
c[7]
c[5]c[4]
456072
1543-89062-31
4563
78
c[1]
3: Web Page Authoring 6INE1020: Introduction to Internet
Engineering
2.5.1 Array Object
An array in JavaScript is an Array object 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 7INE1020: Introduction to Internet
Engineering
2.5.1 Array Object
To allocate 12 elements for integer array cvar 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 methoddocument.writeln( “The value is “ + d[2] );
3: Web Page Authoring 8INE1020: Introduction to Internet
Engineering
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 ); Uses a comma-separated initializer list enclosed in square
brackets
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 9INE1020: Introduction to Internet
Engineering
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 asteriksfor ( 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 10INE1020: Introduction to Internet
Engineering
2.5.1 Array Object
Script output: Printing a histogram
3: Web Page Authoring 11INE1020: Introduction to Internet
Engineering
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 12INE1020: Introduction to Internet
Engineering
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 arrayoutputArray( "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 sortfunction compareIntegers( value1, value2 ) {
return parseInt( value1 ) - parseInt( value2 );}
</SCRIPT></HEAD>
<BODY ONLOAD = "start()"></BODY> </HTML>
3: Web Page Authoring 13INE1020: Introduction to Internet
Engineering
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 14INE1020: Introduction to Internet
Engineering
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 15INE1020: Introduction to Internet
Engineering
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 198for ( var i = 0; i < a.length; ++i )
a[ i ] = 2 * i;
// function called when "Search" button is pressedfunction 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 16INE1020: Introduction to Internet
Engineering
2.5.1 Searching Arrays: Linear Search// Search "theArray" for the specified "key" valuefunction 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 17INE1020: Introduction to Internet
Engineering
2.5.1 Searching Arrays: Linear Search
The array is filled with even number between 0 to 198.
Script output:
3: Web Page Authoring 18INE1020: Introduction to Internet
Engineering
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 19INE1020: Introduction to Internet
Engineering
2.5.1 Multiple-Subscripted Arrays
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 0 Column 2Column 1
Row 0
Row 1
Row 2
Column subscript
Row subscript
Array name
3: Web Page Authoring 20INE1020: Introduction to Internet
Engineering
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 withvar 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 21INE1020: Introduction to Internet
Engineering
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 22INE1020: Introduction to Internet
Engineering
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 23INE1020: Introduction to Internet
Engineering
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 24INE1020: Introduction to Internet
Engineering
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 25INE1020: Introduction to Internet
Engineering
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
declarationsvar color = “blue”;
Strings may be compared with Relational operators Equality operators
3: Web Page Authoring 26INE1020: Introduction to Internet
Engineering
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 27INE1020: Introduction to Internet
Engineering
2.5.2. String ObjectMethod Description
charAt( index ) Returns the character at the specified index. If there is no character at that index, charAt returns an empty string. The first character is located at index 0.
charCodeAt( index ) Returns the Unicode value of the character at the specified index. If there is no character at that index, charCodeAt returns NaN.
concat( string ) Concatenates its argument to the end of the string that invokes the method. This method is the same as adding two strings with the string concatenation operator + (e.g., s1.concat( s2 ) is the same as s1 + s2). The original strings are not modified.
fromCharCode( value1, value2, … )
Converts a list of Unicode values into a string containing the corresponding characters.
indexOf(substring, index )
Searches for the first occurrence of substring starting from position index in the string that invokes the method. The method returns the starting index of substring in the source string (-1 if substring is not found). If the index argument is not provided, the method begins searching from index 0 in the source string.
lastIndexOf( substring, index )
Searches for the last occurrence of substring starting from position index and searching toward the beginning of the string. The method returns the starting index of substring in the source string (-1 if substring is not found). If index is not provided, the method begins searching from end of the source string.
3: Web Page Authoring 28INE1020: Introduction to Internet
Engineering
2.5.2. String ObjectMethod Description
slice( start, end )
Returns a string containing the portion of the string from index start through index end. If the end index is not specified, the method returns a string from the start index to the end of the source string. A negative end index specifies an offset from the end of the string starting from a position one past the end of the last character (so, -1 indicates the last character position in the string).
split( string ) Splits the source string into an array of strings (tokens) where its string argument specifies the delimiter (i.e., the characters that indicate the end of each token in the source string).
substr(start, length )
Returns a string containing length characters starting from index start in the source string. If length is not specified, a string containing characters from start to the end of the source string is returned.
substring( start, end )
Returns a string containing the characters from index start up to but not including index end in the source string.
toLowerCase() Returns a string in which all uppercase letters are converted to lowercase letters. Non-letter characters are not changed.
toUpperCase() Returns a string in which all lowercase letters are converted to uppercase letters. Non-letter characters are not changed.
toString() Returns the same string as the source string.
valueOf() Returns the same string as the source string.
3: Web Page Authoring 29INE1020: Introduction to Internet
Engineering
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 30INE1020: Introduction to Internet
Engineering
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 32INE1020: Introduction to Internet
Engineering
2.5.2. String Object
HTML Markup Methods of String Object
Method Description anchor( name ) Wraps source string in anchor element <A></A> with
name as anchor name. big() Wraps source string in a <BIG></BIG> element.
blink() Wraps source string in a <BLINK></BLINK> element.
bold() Wraps source string in a <B></B> element. fixed() Wraps source string in a <TT></TT> element.
fontcolor( color ) Wraps source string in a <FONT></FONT> element with color as the font color.
fontsize( size ) Wraps source string in a <FONT></FONT> element with size as HTML font size.
italics() Wraps source string in an <I></I> element. link( url ) Wraps source string in an <A></A> with url as the
hyperlink location. small() Wraps source string in a <SMALL></SMALL> element. strike() Wraps source string in a <STRIKE></STRIKE>
element. sub() Wraps source string in a <SUB></SUB> element.
sup() Wraps source string in a <SUP></SUP> element.
3: Web Page Authoring 33INE1020: Introduction to Internet
Engineering
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 timevar current = new Date();
• Allocates memory for object, calls Date object constructor– Constructor is an initializer method for an object
3: Web Page Authoring 34INE1020: Introduction to Internet
Engineering
2.5.3. Date Object
New Date object creationnew 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 35INE1020: Introduction to Internet
Engineering
2.5.4. Math Object
Math object’s methods Allow programmer to perform many common
mathematical calculations
Properties of the Math object
Constant Description Value Math.E Euler’s constant. Approximately 2.718.
Math.LN2 Natural logarithm of 2. Approximately 0.693. Math.LN10 Natural logarithm of 10. Approximately 2.302. Math.LOG2E Base 2 logarithm of
Euler’s constant. Approximately 1.442.
Math.LOG10E Base 10 logarithm of Euler’s constant.
Approximately 0.434.
Math.PI PI - ratio of circle’s circumference to its diameter.
Approximately 3.141592653589793.
Math.SQRT1_2 Square root of 0.5. Approximately 0.707. Math.SQRT2 Square root of 2.0. Approximately 1.414.
3: Web Page Authoring 36INE1020: Introduction to Internet
Engineering
2.5.4. Math Object
Commonly Used Math Object Methods
Method Description Example abs( x ) absolute value of x abs( -3.67 ) is 3.67
ceil( x ) rounds x to the next highest integer ceil( 9.2 ) is 10.0
cos( x ) trigonometric cosine of x (x in radians)
cos( 0.0 ) is 1.0
floor( x ) rounds x to the next lowest integer floor( -9.8 ) is -10.0
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7 max( -2.3, -12.7 ) is -2.3
min( x, y ) smaller value of x and y min( 2.3, 12.7 ) is 2.3 min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y (xy) pow( 2.0, 7.0 ) is 128.0 pow( 9.0, .5 ) is 3.0
3: Web Page Authoring 37INE1020: Introduction to Internet
Engineering
2.5.4. Math Object
Commonly used Math object methodsMethod Description Example
round( x ) rounds x to the closest integer round( 9.75 ) is 10 round( 9.25 ) is 9
sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0.0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x (x in radians)
tan( 0.0 ) is 0.0
3: Web Page Authoring 38INE1020: Introduction to Internet
Engineering
2.5.5. Boolean and Number Objects
Boolean and Number objects 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 39INE1020: Introduction to Internet
Engineering
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 explicitlyvar 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 40INE1020: Introduction to Internet
Engineering
Further Readings
Note: This topic is designed with the objective of providing an introduction to Javascript 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