View
218
Download
1
Embed Size (px)
Citation preview
Electronic Commerce COMP3210
Session 4: Designing , Building and Evaluating e-Commerce Initiatives – Part IIDr. Paul Walcott Department of Computer Science, Mathematics and PhysicsUniversity of the West Indies, Cave Hill CampusBarbados
The Department of Computer Science Mathematics and Physics, University of the West Indies, Cave Hill Campus, Barbados
© 2007 Dr. Paul Walcott
Session Objectives After completing this session you will be
able to: Construct a dynamic Web site
Introduction1,2,3,4,5
So far we have only created static Web pages
In order to create dynamic Web pages we need to use DHTML (Dynamic HTML) and a scripting language
The scripting language that will be used is JavaScript
JavaScript JavaScript unfortunately is not available in
all browsers It is implemented in:
Netscape Navigator 2.0 and later versions Internet Explorer 3.0 and later versions
JavaScript Cont’d JavaScript:
Is client-based Provides simple interactions with the user Provides navigation through pages Validates form information
JavaScript Cont’d JavaScript was not designed to:
Write files to the system server Write files to the client’s machine Read files from the client machine Handle graphics; that is, it does not have
graphic capablities
JavaScript Cont’d Before we can begin writing JavaScript
programs however, the student must first be introduced to computer programming
Computer ProgrammingWhat is a Computer Program? A computer program is:
A computer program is a set of statements or instructions to be used directly or indirectly in a computer in order to bring about a certain result (www.tms.org/pubs/journals/JOM/matters/matters-9710.html )
A computer program requires some input, which is processed to generate a given output
Computer Programming Cont’dWhat is a Computer Program (Cont’d)? When given a problem you must:
Determine the input Determine the outputs Determine the processing required to
transform the inputs to the desired output
Computer Programming Cont’dHow is a Computer Program Described? A computer program is described using an
algorithm An algorithm is like a recipe which describes the set
of steps required to cook a given dish
An algorithm may take several forms, however popular techniques include: Flowcharts Pseudo-code
Computer Programming Cont’dImportant Programming Concepts There are several important concepts that must be
understood in order to write an algorithm and a computer program. These include: Variables Types Assignment Incrementation/decrementation Conditionals Looping Arrays
Computer Programming Cont’dVariables A variable is a name/value pair
E.g. the variable named Price might have the value 10.00, or the variable Count the value 1
Variables in computer programs are associated with a given location in the computer’s memory
Variable names typically begin with a letter (or underscore character) but may include letters, the underscore character and numbers in subsequent characters
Computer Programming Cont’dTemporary Variables A temporary variable is a variable that is
used to temporarily hold a given value An example of when a temporary variable is
required is when the value in two variables need to be swapped around (this is discussed later)
Computer Programming Cont’dVariable Types The variable type specifies the type of information that it
can hold Some common types are:
Integers, e.g. 10 or -20 Floats (or real numbers), e.g. 5.67 Characters, which are single characters enclosed in a single
brace, e.g. ‘a’ or ‘z’ Strings, which are a sequence of characters, e.g. “fred”
An empty string is referred to as a null string, i.e. “” Boolean, which has a value of True or False
Computer Programming Cont’dAssignment In order for a variable to get a value, this value must be
assigned to it Giving a variable a value for the first time is known as
initialisation An assignment may come in several forms, for example:
Count = 1 Product = “Shoes”Where the integer 1 is assigned to the variable count and the string
“Shoes” is assigned to the variable Product
Computer Programming Cont’dAssignment Cont’d Note that the value on the right hand side is
assigned to the variable on the left hand side. In a similar way two variables may be used in an
assignment, e.g.: Count = NewCount
Where the value of the variable NewCount is assigned to the variable Count
Computer Programming Cont’dAssignment Cont’d Using the concept of assignment and
temporary variables the value stored in two variables my be exchanged
Consider the variables a and b as defined below: a = 1 b = 2
Computer Programming Cont’dAssignment Cont’d If we attempted to swap these values directly then
one of the values would be lost:a = bb = aWill result in both a and b being equal to 2
Similarlyb = aa = bWill result in both a and b being equal to 1
Computer Programming Cont’dAssignment Cont’d In order to complete this swap correctly, a
temporary variable needs to be used:temp = aa = bb = temp
Alternativelytemp = bb = aa = temp
Computer Programming Cont’dIncrementation/Decrementation Often in computer programming it is necessary to
count the number of times a given event occurs, or should occur
A variable is often used in this situation and is often called a counter
A Counter may be of two forms: One that increments One that decrements
Computer Programming Cont’dIncrementation/Decrementation Cont’d When incrementing, the value of the
counter is increased by one. e.g. Count = Count + 1
This means that the new value of the variable count will get the old value of count plus one; if count was initially 5 its new value will be 6
Computer Programming Cont’dIncrementation/Decrementation Cont’d When decrementing, the value of the
counter is decreased by one. e.g. Count = Count - 1
This means that the new value of the variable count will get the old value of count minus one; if count was initially 5 its new value will be 4
Computer Programming Cont’dConditionals Often in programming it is necessary to
test whether a given condition has been met e.g. whether the value of the variable count
is equal to 10 This is accomplished through the use of the
conditional statement, if
Computer Programming Cont’dConditionals Cont’d An if statement takes the form:
if (condition) { do something }
For the do something statement to be executed the condition must evaluate to true
Computer Programming Cont’dConditionals Cont’d If we needed to test whether the variable count
had a value of 5, then the following algorithm could be used: if (count = 5) { print “Count equals 5” }
Computer Programming Cont’dConditionals Cont’d Similarly if we needed to test whether the variable count
did not have a value of 5 then the following could be used: if (count <> 5) { print “Count is not equal to 5” }
Note that <> is shorthand for NOT (count = 5)
Computer Programming Cont’dConditionals Cont’d Other conditional operators include:
‘<‘ less than e.g. if (count < 5){ … }
‘>’ greater than e.g. if (count > 5){ … }
Computer Programming Cont’dConditionals Cont’d
Boolean operators include NOT OR AND
Computer Programming Cont’dConditionals Cont’d The NOT operator simply inverts a condition For example, if the value of the variable count is 5, then the condition count = 5 will return true
The condition NOT (count = 5) will therefore return false
Computer Programming Cont’dConditionals Cont’d If a Boolean variable exit, for example is
used, instead of writing: if (exit) { do something }
Which executes the statement do something if exit has a value of true
Computer Programming Cont’dConditionals Cont’d We write: if (NOT(exit)) { do something }
Which executes the statement do something if exit has a value of false
Computer Programming Cont’dConditionals Cont’d The possible inputs and outputs to Boolean
operators are generally illustrated in a truth table Which shows all possible inputs and outputs
Computer Programming Cont’dConditionals Cont’d The truth table for the NOT operator is
illustrated below, where A is a given event:
Computer Programming Cont’dConditionals Cont’d The AND operator requires two events If both of these events are true then the
Boolean condition “first event AND the second event” will yield true
Computer Programming Cont’dConditionals Cont’d The AND operator is often used in the
English language, for example If it does not rain AND I have transportation
then I will go to University The two inputs to this operator are “If it does
not rain” and “I have transportation” The output is true only if both of these inputs
are true
Computer Programming Cont’dConditionals Cont’d In an algorithm we can write the AND
operator in the following way: if ((count = 5) and (name = “BOB”)) { do something }
Computer Programming Cont’dConditionals Cont’d The truth table for the AND operator is
illustrated below:
Computer Programming Cont’dConditionals Cont’d The OR operator is similar to the AND
operator in that it requires two event as input
For true to be output, either of the events must be true
For example, the following English statement uses the OR operator
Computer Programming Cont’dConditionals Cont’d If I arrive early to University OR my class
is cancelled then I will go to lunch with you If the individuals went to lunch together it
meant that one or both of the two events were true, i.e. the person arrived early or their class was cancelled
Computer Programming Cont’dConditionals Cont’d In an algorithm we can write the OR
operator in the following way: if ((count = 5) or (name = “BOB”)) { do something }
Computer Programming Cont’dConditionals Cont’d The truth table for the OR operator is
illustrated below:
Computer Programming Cont’dConditionals Cont’d Sometimes it is required to execute another
statement if the tested condition is not true This can be done using the else clause,
for example:
Computer Programming Cont’dConditionals Cont’d if (count = 5)
{print “Count equals 5”
} else {
print “Count does not equals 5” }
Computer Programming Cont’dConditionals Cont’d If statements may be nested as many times
as the programmer wants, for example: if (faculty = “FPAS”){
if (class = “COMP1130”){
print “The correct course”}
}
Computer Programming Cont’dConditionals Cont’d Testing more than one condition at a time
may be achieved through a compound condition
e.g. the previous nested if statement may be replaced by the compound condition:
Computer Programming Cont’dConditionals Cont’d if ((faculty = “FPAS”) and (class =
“COMP1130”)){
print “The correct course”}
Computer Programming Cont’dLoops Loops are used when a given event needs
to be repeated There are three main types of looping
constructs, these are: The for loop
for loops are used when the number of iterations is known beforehand
Computer Programming Cont’dLoops
The while loop In while loops the condition is tested before looping
The repeat until loop the condition is tested after the statements in the loop have
been executed
To demonstrate how these loops work, all three loops will be used to output the numbers 1 through 5
Computer Programming Cont’dLoops The following for loop prints the numbers
from 1 to 5 for (i = 1 to 5) { print i }
Computer Programming Cont’dLoops The following while loop prints the numbers
from 1 to 5 i = 1 while (i < 6) { print i
i = i + 1 }
Computer Programming Cont’dLoops The following repeat until loop prints
the numbers from 1 to 5 i = 1 repeat { print i
i = i + 1 } until (i = 6)
Computer Programming Cont’dLoops Just like if statements, loops can be nested For example if the user wanted to write a program
to display the numbers 1 through 20, with the numbers 1 – 5, 6 – 10, 11 – 15 and 16 -20 all on different lines then a nested loop could be used Since we need four lines of five numbers each, the
outer loop will loop four times, while the inner loop will loop five times
Computer Programming Cont’dLoops count = 0
for (i = 1 to 4){ for (j = 1 to 5) { count = count + 1 print count } print newline}
Computer Programming Cont’dArrays Arrays are data structures that are used to
represent lists Arrays typically allow the storage of data
of the same type, for example a list of numbers
Computer Programming Cont’dArrays Each element in the array can then be
accessed using the name of the array and the index of the element
For example if the name of the array presented earlier is numbers then numbers[1] = 1, numbers[2] = 7, and so on
Computer Programming Cont’dArrays Note that the first index in an array is
typically 0 rather than 1 Arrays make it easy to sequence through
elements using a loop
Computer Programming Cont’dArrays For example, to print the elements in the
numbers array a for loop could be used: for (i = 1 to 4) {
print numbers[i] }
This would display the numbers 1, 7, 6 and 8
Computer Programming Cont’dArrays In a similar way, if an array, called names,
contained a list of names then a loop could be used to search the list
One search algorithm that may be employed, called linear search, is illustrated below
Computer Programming Cont’dArrays index = 0
while (index < 5){ if (names[index] = “Sam”) { print “Sam was found”
} index = index + 1}
Computer Programming Cont’dArrays One issue with this example is that even if
the item is found, the remainder of the list is still searched
This would be a waste of processing time if we knew before hand that a given name only existed in the list once
Computer Programming Cont’dArrays A number of methods may be used to halt
the search when the given name is found including: a Boolean flag the counter could be set to the terminating
condition
Computer Programming Cont’dArrays The following example uses the Boolean
flag exit:exit = falseindex = 0while ((index < 5) and (not exit)){ if (names[index] = “Sam”) { print “Sam was found”
exit = true }
index = index + 1}
Computer Programming Cont’dArrays
Remember that the loop keeps on looping while the condition ((index < 5) and (not exit)) is true
This condition is false when either index is equal or greater than 5 Or the Boolean variable exit is set to true,
i.e. NOT(true) is false
Computer Programming Cont’dArrays In the next example, the index, index, is
set to the terminating condition:index = 0while (index < 5){ if (names[index] = “Sam”) { print “Sam was found”
index = 5}
index = index + 1}
JavaScript Programs JavaScript programs are either embedded
in the HTML document Or, are held in a file (with a .js extension)
In XHTML 1.0 it is recommended that scripts be held in a file
The SCRIPT element is used to specify a JavaScript program
The SCRIPT Element Function
A container for scripts XHTML 1.0 Example (embedded script) <script type=“text/javascript”> <!-- window.document.write(“Hello web!”); //--> </script>
JavaScript Programs Cont’d
The SCRIPT Element XHTML 1.0 Example (external script)
<script type=“text/javascript” src=“hello.js”></style>
The file hello.js contains
window.document.write(“Hello web!”);
JavaScript Programs Cont’d
The SCRIPT Element Required Attributes
TYPE – Specifies the content type for the script language, e.g. “text/javascript”
Optional Attributes SRC - the location of an external script
The code for external scripts is hidden from the user
JavaScript Programs Cont’d
JavaScript Comments If the characters // appear at the
beginning of a line then the rest of the line is commented out // only comments one line
JavaScript Programs Cont’d
Objects JavaScript is an object-oriented language In JavaScript objects are arranged in
hierarchies and have associated with them: Properties Methods An events
JavaScript Programs Cont’d
The Window Object One of the most important JavaScript
objects is the window object The window object properties include the:
menu bars tool bars scroll bars, and the status line
JavaScript Programs Cont’d
The Window Objects Cont’d To access a given property the following
format is used:
window.defaultstatus = “My Web Page”;
Object Separator Property
JavaScript Programs Cont’d
Properties A property is a characteristic of an object
e.g. length is a property of the String object And defaultstatus is a property of the
window object which changes the Web browser’s status line to
“My Web Page”
JavaScript Programs Cont’d
Methods Methods extract information from objects or
changes an object’s properties, e.g.
Which writes the text “Hello” to the browser window
window.document.write(“Hello”);
Object Method
JavaScript Programs Cont’d
Methods A property is differentiated from a method by the
opening and closing parentheses
JavaScript Programs Cont’d
The Alert Window The alert window is a popup window that
alerts the user of a special condition, e.g.
Which displays an alert window with the text “Hi there!” on one line and “What’s up?” on another
window.alert(“Hi there!\nWhat’s up?”);
JavaScript Programs Cont’d
The Alert Window Cont’d A literal string is passed to the alert method ‘\n’ (new line) characters can be used
within a literal string to create a multi-line message
JavaScript Programs Cont’d
The Confirm Window Allows one of two choices, Ok or Cancel
to a given question If the user selects Ok, a true value is
returned to the script, otherwise a false value is returned
var choice=window.confirm("Do you wish to continue?");
JavaScript Programs Cont’d
String Concatenation Strings may be concatenated (joined)
through the use of the concatenator operator ‘+’, e.g.
Which creates the string “A man Frank and his dog.” from sub strings and a variable
var name = "Frank"; var newString ="A man " + name + "and his dog.";window.document.write(newString);
JavaScript Programs Cont’d
Creating Variables Variables can be created in JavaScript
through the use of the var command, e.g.
Which defines the variable myvar and assigns the value 10 to it
Note that JavaScript variable names are case sensitive
var myvar = 10;
JavaScript Programs Cont’d
The Prompt Window A prompt window contains:
a question a text field (which allows the user to enter
text) and three buttons:
Ok Clear Cancel
JavaScript Programs Cont’d
The Prompt Window Cont’d Pressing Clear clears the contents of the
text field and sets the value to null The prompt window only closes if Ok or
Cancel are pressed
JavaScript Programs Cont’d
The Prompt Window Cont’d Pressing Ok with an empty text field
returns null Pressing Cancel closes the window and
returns null
JavaScript Programs Cont’d
The Prompt Window Cont’d The prompt() method accepts two
parameters The question prompt The default value of the field
var age = window.prompt(“How old are you?”, “10”);
JavaScript Programs Cont’d
Arithmetic Operators Several arithmetic operators are available
in JavaScript:++ Increment -- Decrement- Unary minus * Multiplication/ Division % Modulus+ Addition - Subtraction= Assignment
Combined Assignment*= /= %= += -=
JavaScript Programs Cont’d
Arithmetic Operators Cont’d Examples of the addition and subtraction
operators are given below:var x = 20;var y = 10;// Additionvar result = x + y;window.document.write("<p>x + y = " + result + "</p>");
// Subtractionresult = x - y;window.document.write("<p>x - y = " + result + "</p>");
JavaScript Programs Cont’d
Arithmetic Operators Cont’d When the prompt statement is used to
input numbers they are stored as strings In order to convert them to numbers the parseInt() and parseFloat() methods are required:var itotal = parseInt(prompt("Enter an integer", ""));var ftotal = parseFloat(prompt("Enter a float", ""));
JavaScript Programs Cont’d
Arithmetic Operators Cont’d If the user does not enter an integer in the
prompt window then itotal will evaluate to NaN, not a number This will also happen with ftotal
To test whether a variable contains a valid number use the isNaN() function
JavaScript Programs Cont’d
JavaScript Programs Cont’d For example:
if (isNaN(itotal))
{
window.alert (“Invalid number”);
}
Arithmetic Operators Cont’d It is important to note that there is a known issue with the
parseInt() function If you attempt to parseInt(“08”) or parseInt(“09”) the
result returned is 0 rather than 8 and 9, respectively One solution to the problem is to always include the base
in which the resulting number is in, in this case base 10 Therefore parseInt(“08”,10) = 8 and parseInt(“09”,10) = 9
as expected
JavaScript Programs Cont’d
We now know enough JavaScript to solve a simple problem
The problem simply stated is: Write a program that accepts two numbers
input by the user and display their sum
JavaScript Programs Cont’d
One version of the pseudo code for the solution is:
Input number1
Input number2
result = number1 + number2
Print result
JavaScript Programs Cont’d
Another version could be:
Input first number
Input second number
Add the first number to the
second number
Display the result
JavaScript Programs Cont’d
Utilising the first version of the pseudo code it is clear that we need to define three variables: number1 for the first number
i.e. var number1 = 0 number2 for the second number
i.e. var number2 = 0 result to hold the sum
i.e. var result = 0
JavaScript Programs Cont’d
Next, we need to input the two numbers This can be done using the following JavaScript:
number1 = parseInt( prompt(“Enter first number”,””));
Which prompts the user for the number and converts the returned string to an integer using the function parseInt()
The above is simply repeated for number2
JavaScript Programs Cont’d
Next we need to add the two numbers together which is done using:
result = number1 + number2; And create the message, which includes the
result, to display to the user:var displayString = number1 +
“ + “ + number2 +“ = “ + result;
JavaScript Programs Cont’d
Finally we can display the result to the user using an alert box:
alert(displayString); Or directly to the Web page:
window.document.write( displayString);
JavaScript Programs Cont’d
More JavaScript1,2,4,5
So far you have learnt to write simple JavaScript programs. This knowledge will now be extended through the presentation of: The Math object’s mathematical operators Conditional statements Looping constructs The Array object and how it is used to
manipulate arrays in JavaScript
Some Mathematics To provide additional mathematical
operators the Math object is provided in JavaScript
The Math object includes: Constants Math methods Trig Methods
Some Mathematics Cont’d Constants include:
Math.PI – The value of the constant pi Math.SQRT2 – The square root of 2
Mathematical Methods include: Math.round(x) – rounds the value of x Math.sqrt(x) – the square root of x
Some Mathematics Cont’d Mathematical Methods include (cont’d):
Math.pow(x,y) – xy
Math.random() – generates a random number between 0 – 1, inclusive
Trig methods include: Math.sin(x) – sine Math.cos(x) – cosine Math.tan(x) - tangent
Some Mathematics Cont’dExamples To calculate the square root of the number 9:
window.document.write(Math.sqrt(9));
To calculate 52:
window.document.write(Math.pow(5,2));
Some Mathematics Cont’dExamples Cont’d To calculate sin(90), which is the same thing as
sin(π/2):
window.document.write(Math.sin(Math.PI/2));
To generate a random number between 0 and 100:var num = Math.random()*100;window.document.write(num);
Conditional Statements In JavaScript there are three primary
conditional statement: if if … else switch
Conditional Statements Cont’d The syntax of the if Statement is:
if the expression is non-zero it is true If the expression is zero then it is false
if (expression)Statement;
Conditional Statements Cont’dExample An example of a simple if statement is:
var value = 5;if (value == 5){
window.document.write(“Value is 5”)}
This program outputs “Value is 5”
Conditional Statements Cont’d The syntax of the if .. else statement is:
if the expression is non-zero it is true If the expression is zero then it is false
if (expression) Statement; else Statement;
Conditional Statements Cont’dExamples An example of an if-else statement :
var height = 6; if (height >=6){
window.document.write(“This person is tall”)} else{
window.document.write(“This person is either of average height or short”)}
Conditional Statements Cont’d The syntax of the switch statement is
switch (variable) case value: statement1 … statementndefaultoptional: statement1; … statementn;
Conditional Statements Cont’dExample An example of the switch statement is:
var number = 1;switch (number){
case 1 : window.document.write(“one”);break;
case 2 : window.document.write(“two”);break;
default : window.document.write(“Number not accepted.”);}
Logical Operators Relational operators
< Less than Highest Precedence<= Less than or equal> Greater than>= Greater than or equal== Equal Lowest Precedence!= Not Equal
Logical Operators Cont’d Logical operators
! Not Highest Precedence&& And|| Or Lowest Precedence
Logical Operators Cont’dExamples An example of an if statement with a compound condition is:
var age = 20; firstName = “Bob”; if ((age< 30) && (firstName == “Bob”)){
window.document.write(“Bob Smith”)} else{
window.document.write(“Bob Jackson”)}
Which outputs “Bob Smith”
Logical Operators Cont’dExamples (Cont’d) An example of an if statement with a compound condition is:
var raining = false; busOnTime = true; if (!(raining) && (busOnTime)){
window.document.write(“Going to Campus”)} else{
window.document.write(“Not going to Campus”)}
Logical Operators Cont’dExamples (Cont’d) Which outputs “Not going to campus” Notice that two Boolean variables are use in this
example A Boolean variable accepts the value of true or
false Also notice that it is not required to write
busOnTime == true in the if statement since the variable busOnTime either evaluates to true or false
Iteration JavaScript provides three iteration
statements The for statement The while statement, and The do … while statement
The For Statement The for statement is used when the number
of iterations required is known, e.g. loop five times
The structure of the for loop is:
for (i=0; i<10; i++)
Initial expression Test expression Change expression
The For Statement Cont’d Example: Create a loop that outputs the numbers
1 to 10 on separate lines to the browser Since we need to loop ten times
we set the initial value of the loop variable to 1 We stop once the loop variable reaches greater than
10 We increment the loop variable by one each time
The For Statement Cont’d This is what the code looks like:
for (i=1; i<11; i++){ window.document.write("<div>" + i + "</div>");}
The While Statement The second iteration construct in JavaScript is the
while statement The while statement is primarily used when the
numbers of iterations is not known Just like the for statement a loop variable must be
Initialised Incremented and Tested to see if it has exceeded a given value
The While Statement Cont’d Complete the previous example using the
while instead of the for statement:
var i = 1;while (i < 11){ window.document.write("<div" + i + "</div>"); i++;}
The Do While Statement The do … while statement has a similar
structure to the while statement except that the test is done at the end (instead of the beginning) of each iteration
The Do While Statement Cont’d We will again complete our example using
the do ... while statement
var i = 1;do{ window.document.write("<div>" + i + "</div>"); i++;}while (i < 11);
Compound Statements When a loop terminates when more than
one condition is satisfied, a compound statement should be used. For example:
i=0;while (i<10 && j != 1){ …}
Nested Loops Loops can be nested within each other Example:
Output the numbers 1 to 100 in rows of ten numbers:
Nested Loops Cont’dvar i =0; j = 0;var count = 0;for (i=0; i< 10; i++){ window.document.write("<p>"); for (j=0; j<10; j++) { count++; window.document.write(" " + count + " "); } window.document.write(" </p>");}
Arrays An array is a data structure used to
represent lists, for example the list of numbers {23, 5, 6, 7, 8} may be represented by the array Numbers such that: Numbers[0] = 23 Numbers[1] = 5 Numbers[2] = 6 Numbers[3] = 7
Arrays Cont’d In JavaScript arrays are handled using the Array
object
The array list contains integers, while the array strlist contains a list of strings
Note that the array can be defined and filled at the same time
var list = new Array(23, 5, 6, 7);var strlist = new Array("23", "5");
Arrays Cont’d There are several ways to print the contents
of an array in JavaScript: You can use a function and the prototype
property of the array (this will not be illustrated here)
You can simply use a loop and loop through the array elements
Arrays Cont’d
Notice how Numbers.length returns the number of elements in the array
var i=0;var Numbers = new Array(23, 5, 6, 7);for (i=0; i<Numbers.length; i++) { window.document.write(i + " " + Numbers[i]); }
The length of array
The contents of the array
Arrays Cont’d The output from the program snippet is:
0 23 1 5 2 6 3 7 Note that the numbers 0, 1 ,2 and 3 are the
array indices
Arrays Cont’d Several additional operations may be
performed on arrays including list.sort() – to sort the array
This will correctly sort a list of strings. To sort numeric values a comparator function is required (as shown later)
list.reverse() – to reverse the order of the array
Arrays Cont’d list.push(value) – to append items on the right
hand side (the higher array index) of the array and increasing the array length by 1
value = list.pop() – removes the last element of the array and decreases its size by one
list.unshift(value) – appends the left hand side of the array (the lower array index, i.e. index 0) and increases the array length by 1
Arrays Cont’d value = list.unshift() – removes the first
element from the list and reduces the array length by 1
Arrays Cont’dSorting an Array of Numbers Earlier we learnt how to create and sort an array
of strings Sorting an array of numbers requires a little more
effort To sort an array in numeric order (rather than
lexiographic/dictionary order) a comparator function is required
The comparator function accepts two parameters, x and y and returns a result based on which parameter is greater, x or y
Sorting an Array of Numbers For an ascending order sort:
if x < y return a negative number if x == y return 0 if x > y return a positive number
function ascending (x,y){ return x-y;}
Arrays Cont’d
For an descending order sort: if y < x return a negative number if x == y return 0 if y > x return a positive number
function descending (x,y){ return y-x;}
Arrays Cont’d
The following JavaScript sorts a list in ascending numeric order:
To sort the same list in descending order
Note that ascending and descending are the functions defined earlier
var list = new Array(100, 50, 10, 20);list.sort(ascending);
var list = new Array(100, 50, 10, 20);list.sort(descending);
Arrays Cont’d
Arrays Cont’dAssociative Arrays Another type of array that is available in
JavaScript is an associative array An associative array is defined just like an
ordinary array except that its index is a string rather than a number
Arrays Cont’d For example, if we wanted to store the telephone
number of our friends we could use the following associative array:
var myPhoneNumbers = new Array(); myPhoneNumbers[“john”] = “4296789”; myPhoneNumbers[“frank”] = “4277777”;
window.document.write(MyPhoneNumbers[“john”]);
Even More JavaScript So far we have discussed:
Mathematical operators, conditional statements, iterations, arrays and basic input
Now we will discuss: Functions Events handlers Some pre-defined objects in JavaScript
Functions Functions are used when it is necessary to repeat
the same code in several places in a given program
If a function is used, it minimises the number of changes required if a part of the repeated code needs to be corrected
This is crucial when considering the cost of software maintenance
Functions Cont’dSome Terminology: Function Call: Calling a function is the same as
using it Function Caller: This is the program that calls
the function Return Value: Many functions return values to
the user to indicate errors or successful execution Parameter: This allows user supplied data to be
passed to the function
Functions Cont’d In the example below the window.prompt()
function is called by the JavaScript program (the calling function) and a string value is returned
var name = window.prompt(“Please enter your name”, “”);
Returned value Function call Parameters
Functions Cont’d In JavaScript a function definition has the
following syntax:
function name (<parameter list>){ statement1; … statementn;}
Functions Cont’d The function print() prints the message,
passed as a parameter, to the Web page:
and return the value 1 to the calling function
//Outputs a message to the browserfunction print(message){ window.document.write(message); return 1;}
Functions Cont’d There are some general rules to follow when
using functions A function should perform only one task, and the
function name should reflect that task e.g. the function CalculateIncomeTax() should calculate
income tax based on the input parameters This helps with software reuse
The details of a function should be concealed from the calling function
Functions Cont’d Return results to the calling function rather
than printing them on the screen Unless the purpose of the function was to output
information to say a Web page
Function names must start with an alphabetic character, or underscore Subsequent characters may be alphabetic or
numeric or the underscore character
Functions Cont’d When writing a function it is important that
you document it so that it is easily maintainable
When documenting include: The purpose of the function An example of the function syntax A description of all the parameters
Functions Cont’d An example of documentation for a
function is illustrated below:Function: myRoundPlaces()Purpose: Rounds a floating point number to the specified decimal placesSyntax: myRoundPlaces(number, places)Parameters: number - the floating point number to be rounded places - the number of decimal places
Functions Cont’d A JavaScript function may appear in the <head> or <body> of an HTML document
And may be embedded within the HTML document or stored in an external script Remember in XHTML 1.0 it is recommended
that external scripts be used
Event Handlers An event handler executes a piece of code
based on a given action e.g. the clicking of a button
Event handlers begin with the word “on”, e.g. onclick, ondblclick, onmousedown, onmouseup,
onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
Event Handlers The format of an event handler is:
In this example the text “My Web Page” is written to the status bar
onMouseOut = “window.status=‘My Web Page’;return true”
Event handler Code segment
Event Handlers Cont’d For example to change the status bar as the
mouse moves over a hyperlink, the following code may be used:
<a href=“www.google.com” onMouseOver = “window.status = ‘A popular search engine’;
return true”>http://www.google.com</a>
Event Handlers Cont’d In addition you can call a JavaScript function on
a given event. For example: <div onClick="helpUs()">Please click me!</div>
Where the function helpUs() is defined as:
function helpUs() { window.alert("Help is on the way!"); }
JavaScript Objects JavaScript has several predefined object Two of these objects will be briefly
described here: String Date
JavaScript Objects Cont’dThe String Object To define a string simply use:
var myString = “Hello there!”; The length of the string is given by the
length property, for example the length of myString is:
var mylen = myString.length;
JavaScript Objects Cont’dThe String Object To convert a number to a string in
JavaScript you use the toString() method of the String class. For example:
var myNum = 6578;
var myStr = myNum.toString();
JavaScript Objects Cont’dThe String Object Strings are JavaScript objects and have a variety
of associated methods A useful method is substring(start,
stop) which creates a new string by extracting the characters between start and stop-1, e.g.
which returns the substring “is a String”
var str = "This is a string";window.document.write(str.substring(5,16));
JavaScript Objects Cont’dThe String Object If you needed to determine the first
character of a given string in a list then the charAt() method could be used:
var names = new Array ("Fred", "John", "Frank");window.document.write(names[0].charAt(0));
JavaScript Objects Cont’dThe String Object The split() method allows a string to be
split into separate strings (in an array) at a given character.
For example, we could split the string “Hello to the world” at the space character This will create the four strings (in an array)
“Hello”, “to”, “the” and “world”
JavaScript Objects Cont’dThe String Object var myString =“Hello to the world”; var temp = new Array(); temp = myString.split(‘ ‘); Which creates the array elements 0 -3: temp[0] = ‘Hello’; temp[1] = ‘to’; temp[2] = ‘the’; temp[3] = ‘world’;
JavaScript Objects Cont’dThe Date Object The Date object allows the user to work with
times and dates To create a Date object use the following
JavaScript
Which creates the object using the current date and time
var now = new Date();
JavaScript Objects Cont’dThe Date Object Several methods are provided by the Date object
including: getHours() – which returns the current hour getMinutes() – which returns the current minute getSeconds() – which returns the current second getYear() – which returns the current year (or
getFullYear()) getMonth() – which returns the current month getDate() – which returns the current day
JavaScript Objects Cont’dThe Date Object Similarly a number of methods have been defined
in the Date object that allows the date to be set setHours() – which sets the current hour setMinutes() – which sets the current minute setSeconds() – which sets the current second setYear() – which sets the current year (or
setFullYear()) setMonth() – which sets the current month setDate() – which sets the current day
JavaScript Objects Cont’dThe Date Object When creating a new Date object you can
set the time and date of that object e.g. to set the time and date to February 1,
2004, 10:00:00
Where the parameters for the Date object are:
var now = new Date(2004, 2, 1, 10, 0, 0);
Date(year, month, day, hours, minutes, seconds);
References[1] Darnell, Rick, et al., “HTML4: Unleased”, Sams.net Publishing, First Edition,
1997
[2] W3C, “HyperText Markup Language (HTML) Home Page”, 2004. Online document available at “http://www.w3c.org/MarkUp/”
[3] Deitel, H., Deitel, P., Nieto, Frank, L., Lin, Ted, M., Sadhu, Praveen, “XML: How to Program”, Prentice-Hall Inc., 2001
[4] Anderson-Freed, Susan, “Weaving a Website: Programming in HTML, Javascript, Perl and Java”, Prentice Hall , 2002
[5] Koch, Stefan, “Voodoo’s Introduction to JavaScript”, 1998. Online document available at “http://oopweb.com/JavaScript/Documents/jsintro/Volume/part1/part1.htm”