Graduate Assignment 2
Weeks 6 & 7
by Larry Adams
HTML
<h2>Graduate Assignment 2 for weeks 6 & 7</h2>
<p>The purpose of this assignment is to test your ability to work with conditions, functions, objects, and output.</p>
<p>JavaScript has 4 methods of displaying your output:</p>
<ol>
<li>Window Alert</li>
<li>HTML Output</li>
<li>HTML Element</li>
<li>Browser Console</li>
</ol>
<p>Your assignment is to write a array, condition, function, and object that demostrates each one of the 4 displays.
<h3>Conditional Statement with a Function</h3>
<p>Type in a number to convert temperature and show your output</p>
<input type=text id=temp>
<br><input type="button" id=ctof value="to °F"> <input type="button" id=ctof2 value="to °C">
<br><br>
<output></output>
<h3>Displaying an Object</h3>
JavaScript
//JavaScript can "display" data in different ways:
/* Source is from Piotr Zalewa and Oskar Krawczyk at http://jsfiddle.net/estelle/cu2yB/ which is a example of converting temp
/*
Creating a alert box, using window.alert()
Creating a HTML output using document.write()
Creating a browser console, using console.log()
Creating a HTML element, using innerHTML
*/
var temperatures = function(t) {
var output, given, result, opposite;
given = document.getElementById('temp').value;
if (t === "C") {
result = 1.8 * (+given) + 32;
opposite = "F";
} else {
result = (given - 32) / 1.8;
opposite = "C";
}
if (result % 1 !== 0) {
console.log(result % 1);
result = result.toFixed(2);
}
if (given || given === "0") {
output = given + " \u00b0" + t + " is equal to " + result + " \u00b0" + opposite;
} else {
output = "error: number expected";
}
document.querySelector('output').innerHTML = output;
}
document.getElementById('ctof').addEventListener('click', function(){temperatures('C');})
document.getElementById('ctof2').addEventListener('click', function(){temperatures('F');})
/* Displaying an alert and console output */
/* Developer console required */
// simple array
var myObj = [1, 2, 3];
// instanceof tests
if (myObj instanceof Array) {
alert("is Array");
};
if (myObj instanceof Object) {
alert("is Object");
};
// print array to console
console.log(myObj);
// add a method to the Array class (Array of numbers expected)
Array.prototype.max = function() {
var max = this[0];
for (var i = 1; i < this.length; i++) {
max = (this[i] > max) ? this[i] : max;
}
return max;
}
// alert max value of array
alert("Max is: "+myObj.max());
// iterate myObj properites - (alert only non-function, i.e. array members)
for (var key in myObj) {
console.log("Key:" + key + " /...