~~SLIDESHOW~~
Contact Hour 8: To be discussed on Wednesday 13th February, 2013.
Lecturer: Dr Chris P. Jobling.
Continuing our introduction to JavaScript with a look at control statements, objects, arrays and functions.
These slides and notes are based on Chapter 4 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006. with additional examples and explanation from Chris Bates, Web Programming: Building Internet Applications, 3rd Edition, John Wiley, 2006.
We continue our quick tour of the basics of JavaScript.
Contents of this Lecture
At the end of this lecture you should be able to answer these questions:
==
and ===
? while
statement and a do
-while
statement? I have decided to use jsFiddle to host the examples for this session as this provides a nice way to demonstrate the code and for you to play with the code afterwards. If you want to run the examples yourself you can make use of the template HTML and CSS that has been provided in the examples folder.
Use the script-tag in the provided HTML template to load the external JavaScript file for the example you wish to see run.
true
or false
Primitive values can be interpreted as booleans (truthy values)
true
unless it is empty or “0”
true
unless it is zero null
or undefined
it is always false
==
, !=
, <
, >
, <=
, >=
===
and !==
==
and !=
, except that no coercions are done (operands must be identical)
Generally, for safety, you want to avoid coercion as it adds an element of uncertainty, use ===
and !==
rather than ==
and !=
.
&&
, ||
, and !
toString
, to allow results of a control expression to be printed (“true”
or “false”
) if-then-else
(clauses can be either single statements or compound statements)var a = 2, b = 4, element = $('#result'), message; if (a > b) { message = a + " is greater than " + b; console.log(message); element.append("<p>" + message + "</p>"); } else { message = a + " is not greater than " + b; console.log(message); element.append("<p>" + message + "</p>"); a = b; } message = "Now a === b is " + (a === b); console.log(message); element.append("<p>" + message + "</p>");
switch (expression) { case value_1: // value_1 statements case value_2: // value_2 statements . . . default: // default statements] }
break
at the end of each conditionUsing a script to set the border properties of a table (See borders2.html).
1. Initial dialogue
2. Result
3. Code
var bordersize, table, element; element = $('#result'); bordersize = prompt("Select a table border size \n" + "0 (no border) \n" + "1 (1 pixel border) \n" + "4 (4 pixel border) \n" + "8 (8 pixel border) \n"); table = ""; switch (bordersize) { case "0": table += "<table>"; break; case "1": table += "<table border = '1'>"; break; case "4": table += "<table border = '4'>"; break; case "8": table += "<table border = '8'>"; break; default: console.error("Error - invalid choice: " + bordersize + "\n"); table += "<table>"; } table += "<caption> 2003 NFL Divisional Winners </caption>"; table += "<tr>" + "<th />" + "<th> American Conference </th>" + "<th> National Conference </th>" + "</tr>" + "<tr>" + "<th> East </th>" + "<td> New England Patriots </td>" + "<td> Philadelphia Eagles </td>" + "</tr>" + "<tr>" + "<th> North </th>" + "<td> Baltimore Ravens </td>" + "<td> Green Bay Packers </td>" + "</tr>" + "<tr>" + "<th> West </th>" + "<td> Kansas City Chiefs </td>" + "<td> St. Louis Rams </td>" + "</tr>" + "<tr>" + "<th> South </th>" + "<td> Indianapolis Colts </td>" + "<td> Carolina Panthers </td>" + "</tr>" + "</table>"; console.log(table); element.append(table);
while (control_expression) statement or compound
for (init; control; increment) statement or compound
do-while
do statement or compound while (control_expression)
// date.js // Illustrates the use of the Date object by // displaying the parts of a current date and // using two Date objects to time a calculation var element = $('#result'); // Get the current date var today = new Date(); // Fetch the various parts of the date var dateString = today.toLocaleString(), day = today.getDay(), month = today.getMonth(), year = today.getFullYear(), timeMilliseconds = today.getTime(), hour = today.getHours(), minute = today.getMinutes(), second = today.getSeconds(), millisecond = today.getMilliseconds(); // Display the parts of the date element.append("<p>Date: " + dateString + "<br />" + "Day: " + day + "<br />" + "Month: " + month + "<br />" + "Year: " + year + "<br />" + "Time in milliseconds: " + timeMilliseconds + "<br />" + "Hour: " + hour + "<br />" + "Minute: " + minute + "<br />" + "Second: " + second + "<br />" + "Millisecond: " + millisecond + "</p>"); // Time a loop var dum1 = 1.00149265, product = 1; var start = new Date(); for (var count = 0; count < 10000; count++) { product = product + 1.000002 * dum1 / 1.00001; } var end = new Date(); var diff = end.getTime() - start.getTime(); element.append("<p>The loop took " + diff + " milliseconds</p>");
At the end of this lecture you should be able to answer these questions:
new
operator and the Object constructor have? Lets play with some objects.
new
Object
constructor, as invar myObject = new Object();
var myAirplane = new Object(); myAirplane.make = "Cessna"; myAirplane.model = "Centurian";
new
var property1 = myAirplane.make; var property2 = myAirplane["model"];
myAirplane.make = "Boeing"; myAirplane["model"] = "767";
delete myAirplane.model;
var myAirplane = { make: "Cessna", model: "Centurion" };
Please take careful note of the puctuation!
for (identifier in object) statement or compound
for (var property in myAirplane) { console.log(property + ": " + myAirplane[property]); }
At the end of this lecture you should be able to answer these questions:
for-in
statement. length
property of an Array object and the actual number of existing elements in the object? join
method of Array
. slice
method when it is given just one parameter. Fiddle with arrays
length
property stores the lengthnew
, or by assigning an array literalvar myList = new Array(24, "bread", true); var myList2 = [24, "bread", true]; var myList3 = new Array(24);
myList[122] = "bitsy"; // length is 123
length
property is writeable, you can set it to make the array any length you like, as inmyList.length = 150;
/* insert_names.html The script in this document has an array of names, name_list, whose values are in alphabetic order. New names are input through prompt. Each new name is inserted into the name array, after which the new list is displayed. */ // The original list of names var name_list = ["Al", "Betty", "Kasper", "Michael", "Roberto", "Zimbo"]; // working variables var new_name, index, last, result, element = $('#result'); // Loop to get a new name and insert it while (new_name = prompt("Please type a new name", "")) { // Loop to find the place for the new name last = name_list.length - 1; while (last >= 0 && name_list[last] > new_name) { name_list[last + 1] = name_list[last]; last--; } // Insert the new name into its spot in the array name_list[last + 1] = new_name; // Display the new array result = "<p><b>The new name list is:</b><br />"; element.append(); for (index = 0; index < name_list.length; index++) { result += name_list[index] + "<br />"; } result += "</p>"; element.append(result); } //** end of the outer while loop
join
– e.g., var listStr = list.join(“, ”);
reverse
sort
– e.g., names.sort();
concat
– e.g., newList = list.concat(47, 26);
slice
listPart = list.slice(2, 5); listPart2 = list.slice(2);
toString
push
, pop
, unshift
, and shift
// nested_arrays.html An example to illustrate an // array of arrays var element = $('#result'), result_text; // Create an array object with three arrays as its // elements var nested_array = [ [2, 4, 6], [1, 3, 5], [10, 20, 30] ]; // Display the elements of nested_list result_text = "<p>"; for (var row = 0; row <= 2; row++) { result_text += "Row " + row + ": "; for (var col = 0; col <= 2; col++) { result_text += nested_array[row][col] + " "; } result_text += "<br />"; } element.append(result_text + "</p>");
At the end of this lecture you should be able to answer these questions:
return
statement? function function_name([formal_parameters]) { -- body - }
return
statementreturn
statement, or if the end of the function is reached, undefined
is returned return
has no parameter, undefined
is returned fun
is the name of a function,ref_fun = fun; // . . . ref_fun(); /* A call to fun */
undefined
)arguments
, which has the length
property// parameters.html The params function and a test // driver for it. This example illustrates // function parameters var element = $('#result'); // Function describe_params // Parameters: two named parameters and one unnamed // parameter, all numbers // Returns: nothing function describe_params(a, b) { var text = "Function <em>describe_params</em> was passed " + arguments.length + " parameter(s) <br />" + "Parameter values are: <br />"; for (var arg = 0; arg < arguments.length; arg++) { text += arguments[arg] + "<br />"; } text += "In addition named-parameter <em>a</em> was " + a + " and <em>b</em> was " + b; return text; } // A text driver for params element.append("<p>" + describe_params("Mozart") + "</p>"); element.append("<p>" + describe_params("Mozart", "Beethoven") + "</p>"); element.append("<p>" + describe_params("Mozart", "Beethoven", "Tchaikowsky") + "</p>");
sort
methodfunction num_order(a, b) {return a - b;}
num_list
with:num_list.sort(num_order);
Function as variable:
var function_name = function ([formal_parameters]) { -- body - };
function_name
.// medians.js // A function and a function tester // Illustrates array operations var element = $('#result'); /* Function median Parameter: An array of numbers Return value: The median of the array */ var median = function (list) { list.sort(function (a, b) { return a - b; }); var list_len = list.length; // Use the modulus operator to determine whether // the array's length is odd or even // Use Math.floor to truncate numbers // Use Math.round to round numbers if ((list_len % 2) == 1) { return list[Math.floor(list_len / 2)]; } else { return Math.round((list[list_len / 2 - 1] + list[list_len / 2]) / 2); } }; // end of function median -- note semicolon var my_list_1 = [8, 3, 9, 1, 4, 7], my_list_2 = [10, -2, 0, 5, 3, 1, 7], med; med = median(my_list_1); element.append("<p>Median of [" + my_list_1 + "] is: " + med + "</p>"); med = median(my_list_2); element.append("<p>Median of [" + my_list_2 + "] is: " + med + "</p>");
function Plane(newMake, newModel, newYear){ this.make = newMake; this.model = newModel; this.year = newYear; } myPlane = new Plane("Cessna", "Centurian", "1970");
Note by convention, constructors use upper case names to distinguish them from ordinary functions. Think proper noun.
display: function() { console.log("Make: " + this.make); console.log("Model: " + this.model); console.log("Year: " + this.year); }
myPlane.display();
Programming in JavaScript
At the end of this lecture you should be able to answer these questions:
==
and ===
? while
statement and a do
-while
statement? At the end of this lecture you should be able to answer these questions:
new
operator and the Object constructor have? At the end of this lecture you should be able to answer these questions:
for-in
statement. length
property of an Array object and the actual number of existing elements in the object? join
method of Array
. slice
method when it is given just one parameter. At the end of this lecture you should be able to answer these questions:
return
statement? There are a few more review questions available. You might need to refer to a good JavaScript reference to answer them all.
Use jsFiddle or some other method to write, test and debug (if necessary) HTML files that include JavaScript scripts for the following problems. When required to write functions, you must include a script to test the function with at least two different data sets.
console.log
to produce the output.prompt
, which is the number of the Fibonacci number required as output.no_zeros
; Parameter: An array of numbers; Result: The array must be modified to remove all zero values. Returns: true
if the given array included zeros; false
otherwise.More basic javascript exercises, taken from Chapter 4 of Robert W. Sebasta, Programming the World-Wide Web, 3rd Edition, Addison Wesley, 2006., are available.
Text processing with regular expressions