Title: Lecture 6: Introduction to Javascript II
1Lecture 6 Introduction to Javascript II
- Javascript Objects
- Array
- String
- Date
- Math
- Boolean
22.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
32.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
42.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)
c4 - 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
52.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 expression
- arrayName.length
62.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
72.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 d2 )
82.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 n2 - n2 will appear undefined until it is initialized
92.5.1 Array Object
ltHTMLgt ltHEADgt ltTITLEgt Histogram Printing Program
lt/TITLEgt ltSCRIPT LANGUAGE "JavaScript"gt
function start() var theArray 19, 3, 15,
7, 11, 9, 13, 5, 17, 1 document.writeln(
"ltTABLE BORDER '1' WIDTH '100'gt"
) document.writeln( "ltTRgtltTD WIDTH
'100'gtltBgtElementlt/Bgt" "ltTD WIDTH
'100'gtltBgtValuelt/Bgt" "ltTDgtltBgtHistogramlt/Bgtlt/T
Rgt" ) for ( var i in theArray )
document.writeln( "ltTRgtltTDgt" i
"ltTDgt" theArray i "ltTDgt" ) //
print a bar of asteriks for ( var j 1 j lt
theArray i j ) document.writeln( ""
) document.writeln( "lt/TRgt"
) document.writeln( "lt/TABLEgt"
) lt/SCRIPTgt lt/HEADgt ltBODY ONLOAD
"start()"gtlt/BODYgt lt/HTMLgt
102.5.1 Array Object
- Script output Printing a histogram
112.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
122.5.1 Sorting Arrays
ltHTMLgt ltHEADgt ltTITLEgt Sorting an Array with Array
Method sort lt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt function start() var a
10, 1, 9, 2, 8, 3, 7, 4, 6, 5 document.write
ln( "ltH1gtSorting an Arraylt/H1gt" ) 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( "ltPgt" header
theArray.join( " " ) "lt/Pgt" ) //
comparison function for use with sort function
compareIntegers( value1, value2 ) return
parseInt( value1 ) - parseInt( value2
) lt/SCRIPTgt lt/HEADgt ltBODY ONLOAD
"start()"gtlt/BODYgt lt/HTMLgt
132.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
142.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
152.5.1 Searching Arrays Linear Search
- Example of searching an array for an integer
number
ltHTMLgt ltHEADgt ltTITLEgt Linear Search of an Array
lt/TITLEgt ltSCRIPT LANGUAGE "JavaScript"gt var a
new Array( 100 ) // create an Array // fill
Array with even integer values from 0 to 198 for
( var i 0 i lt 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.v
alue "Value not found"
162.5.1 Searching Arrays Linear Search
// Search "theArray" for the specified "key"
value function linearSearch( theArray, key )
for ( var n 0 n lt 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 lt/SCRIPTgt lt/
HEADgt ltBODYgt ltFORM NAME "searchForm"gt ltPgtEnter
integer search keyltBRgt ltINPUT NAME "inputVal"
TYPE "text"gt ltINPUT NAME "search" TYPE
"button" VALUE "Search" ONCLICK
"buttonPressed()"gtltBRgtlt/Pgt ltPgtResultltBRgt ltINPU
T NAME "result" TYPE "text" SIZE
"30"gtlt/Pgt lt/FORMgt lt/BODYgt lt/HTMLgt
172.5.1 Searching Arrays Linear Search
- The array is filled with even number between 0 to
198. - Script output
182.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 elements row
- Second subscript identifies elements column
- m-by-n array
- An array with m rows and n columns
192.5.1 Multiple-Subscripted Arrays
- Double-scripted array with three rows and four
columns
202.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
212.5.1 Multiple-Subscripted Arrays
ltHTMLgt ltHEADgt ltTITLEgt Initializing
Multidimensional Arrays lt/TITLEgt ltSCRIPT LANGUAGE
"JavaScript"gt 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( "ltH2gt"
header "lt/H2gtltTTgt" ) for ( var i in theArray
) for ( var j in theArray i )
document.write( theArray i j " "
) document.writeln( "ltBRgt" ) document.w
riteln( "lt/TTgt" ) lt/SCRIPTgt lt/HEADgt ltBODY
ONLOAD "start()"gtlt/BODYgt lt/HTMLgt
222.5.1 Multiple-Subscripted Arrays
- The script uses nested for/in structures to
traverse the arrays and output their contents - Script output
232.5.2. String Object
- String Object
- JavaScripts string and character processing
capabilities - Appropriate for developing
- Text editors
- Word processors
- Page layout software
- Computerized typesetting systems
- Other kinds of text-processing software
242.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.
252.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
262.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
272.5.2. String Object
282.5.2. String Object
292.5.2. Split String Example
lthtmlgt ltheadgt
lttitlegtString Method split and substringlt/titlegt
ltscript type "text/javascript"gt
function splitButtonPressed()
var strings
myForm.inputVal.value.split( " " )
myForm.output.value strings.join( "\n" )
myForm.outputSubstring.value
myForm.inputVal.value.substring( 0, 10 )
lt/scriptgt lt/headgt
302.5.2. Split String Example
ltbodygt ltform name "myForm" action
""gt ltpgtEnter a sentence to split
into wordsltbr /gt ltinput name
"inputVal" type "text" size "40" /gt
ltinput name "splitButton" type "button"
value "Split" onclick
"splitButtonPressed()" /gtlt/pgt
ltpgtThe sentence split into words isltbr /gt
lttextarea name "output" rows "8"
cols "34"gt lt/textareagtlt/pgt
ltpgtThe first 10 characters of the
input string are ltinput name
"outputSubstring" type "text"
size "15" /gtlt/pgt lt/formgt
lt/bodygt lt/htmlgt
312.5.2. Split String Example
322.5.2. String Object
- HTML Markup Methods of String Object
332.5.3. Date Object
- JavaScripts 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
342.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
352.5.4. Math Object
- Math objects methods
- Allow programmer to perform many common
mathematical calculations - Properties of the Math object
362.5.4. Math Object
- Commonly Used Math Object Methods
372.5.4. Math Object
- Commonly used Math object methods
382.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 )
392.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
40Further 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/javascr
ipt.html