World Wide Web Programming 13 - Decisions, loops, functions and objects in JavaScript
Comparison Operators == < > = !=
The if statement
if (roomTemp > 90) { roomTemp = roomTemp - 10; }
Example
<SCRIPT LANGUAGE=JavaScript> var degFahren = prompt("Enter the degrees Fahrenheit",32); var degCent; degCent = 5/9 * (degFahren - 32); document.write(degFahren + "\xB0 Fahrenheit is " + degCent + "\xB0 centigrade
"); if (degCent < 0) { document.write("That's below the freezing point of water"); } if (degCent == 100) document.write("That's the boiling point of water");
Logical Operators AND -> && OR -> || NOT -> !
Multiple Conditions Example
<SCRIPT LANGUAGE=JavaScript> var myAge = prompt("Enter your age",30); if (myAge >= 0 && myAge = 0 && myAge = 80 || myAge = 30 && myAge = 80 && myAge var secretNumber = prompt("Pick a number between 1 and 5:", ""); secretNumber = parseInt(secretNumber); switch (secretNumber) { case 1: document.write("Too low!"); break; case 2: document.write("Too low!"); break; case 3: document.write("You guessed the secret number!"); break; case 4: document.write("Too high!"); break; case 5: document.write("Too high!"); break; default: document.write("You did not enter a number between 1 and 5."); break; } document.write("
Execution continues here");
The for Loop
for (loopCounter=1; loopCounter var degFahren = new Array(212, 32, -459.15); var degCent = new Array(); var loopCounter;
32);
for (loopCounter = 0; loopCounter = 0; loopCounter--) { document.write("Value " + loopCounter + " was " + degFahren[loopCounter] + " degrees Fahrenheit"); document.write(" which is " + degCent[loopCounter] + " degrees centigrade
"); }
The for…in
var index; for (index in myArray) { document.write(myArray[index]); }
While and do…while
while (degCent != 100) { // run code } do { userAge = prompt (“Please enter your age”,””); } while (isNaN(userAge) == true)
Break and continue Same use than in PHP Break will stop a loop Continue will jump to the next iteration
Creating functions
function convertToCentigrade (degFahren) { var degCent; degCent = 5/9 * (degFahren - 32); return degCent;
} To use it later on…
• var myTemp; myTemp = convertToCentigrade(212);
Using objects As you should know an object is an element that can be defined by its properties For example an object “car” can have the properties “color” “brand” or “mileage” Each object can have a set of methods that correspond to the actions you can do with the object
Creating and using an object var myVar = new ObjectName(optional parameters) var myArray = new Array();
• note that Array is an object
var myDate = new Date(); myArray.length myArray.sort();
The String Objects var string1 = new String (“Hello”); var string2 = new String (123); var string3 = new String (123.456); var string1 =“Hello”; string.length string.charAt(position); string.charCodeAt(position);
function checkCharType(charToCheck) { var returnValue = "O"; var charCode = charToCheck.charCodeAt(0); if (charCode >= "A".charCodeAt(0) && charCode = "a".charCodeAt(0) && charCode = "0".charCodeAt(0) && charCode var myNumber = prompt("Enter the number to be rounded",""); document.write("
The number you entered was " + myNumber + "
"); document.write("
The rounding results for this number are
"); document.write("
"); document.write("Method | Result |
"); document.write("parseInt() | "+ parseInt(myNumber) +" |
"); document.write("ceil() | " + Math.ceil(myNumber) + " |
"); document.write("floor() | "+ Math.floor(myNumber) + " |
"); document.write("round() | " + Math.round(myNumber) +" |
"); document.write("
")
Getting random numbers
<script language=JavaScript> var throwCount; var diceThrow; for (throwCount = 0; throwCount < 10; throwCount++) { diceThrow = (Math.floor(Math.random() * 6) + 1); document.write(diceThrow + "
"); }
Array Objects
var myArray = new Array(); myArray.length contactArray = myArray.concat(myArray2); myArray.slice(b,e) myArray.join(“
”)
• This would output a string with all the elements of an array using
as a separator
myArray.sort() myArray.reverse()
Example
var myShopping = new Array("Eggs","Milk","Potatoes","Cereal","Banana"); var ord = prompt("Enter 1 for alphabetical order, and -1 for reverse order", 1); if (ord == 1) { myShopping.sort(); document.write(myShopping.join("
")); } else if (ord == -1) { myShopping.sort(); myShopping.reverse(); document.write(myShopping.join("
")); } else { document.write("That is not a valid input"); }
The Date object
var date = new Date(); var date = new Date(949278000000); • We put the number of milliseconds passed since Jan, 1 1970 at 00:00:00 • This example represents Jan 31, 2000 00:20:00 GMT
var date = new Date(“31 January 2000”); var date = new Date(2000,0,31,15,35,20,20); • Year, month, day, hour, minute, second, millisecond
Getting Values myDate.getDate() myDate.getDay() myDate.getMonth() myDate.FullYear()
Retrieving the current date
var months = new Array("January","February","March","April","May","June","July", "August","September","October","Novemeber","Decemeber"); var dateNow = new Date(); var yearNow = dateNow.getFullYear(); var monthNow = months[dateNow.getMonth()]; var dayNow = dateNow.getDate(); var daySuffix; switch (dayNow) { case 1: case 21: case 31: daySuffix = "st"; break; case 2: case 22: daySuffix = "nd"; break; case 3: case 23: daySuffix = "rd"; break; default: daySuffix = "th"; break; } document.write("It is the " + dayNow + daySuffix + " day ");document.write("in the month of " + monthNow); document.write(" in the year " + yearNow);
Setting Date myDate.setDate(num) myDate.setMonth(num) myDate.setYear(year)
Getting time values myDate.getHours() myDate.getMinutes() myDate.getSeconds() myDate.getMilliseconds()
Showing the current time
var var var var var
greeting; nowDate = new Date(); nowHour = nowDate.getHours(); nowMinute = nowDate.getMinutes(); nowSecond = nowDate.getSeconds();
if (nowMinute < 10) nowMinute = "0" + nowMinute; if (nowSecond < 10) nowSecond = "0" + nowSecond; if (nowHour < 12) { greeting = "Good Morning"; } else if (nowHour < 17) { greeting = "Good Afternoon"; } else { greeting = "Good Evening"; } document.write("
" + greeting + " and welcome to my website
") document.write("According to your clock the time is "); document.write(nowHour + ":" + nowMinute + ":" + nowSecond);
Setting time myDate.setHours() myDate.setMinutes() myDate.setSeconds() myDate.setMilliseconds()