Examples of COMP9633
The basics you learned in COMP9633
by Alma Grace
JavaScript
/* Loop through an array */
myarr = ["foo", "bar", "baz"];
for (var i = 0; i < myarr.length; i++) {
console.log(myarr[i]);
}
/* Loop through an object */
myobj = {
foo: "Something",
bar: "Another thing"
};
for (var i in myobj) {
console.log(i + ": " + myobj[i]);
}
function myfunction(myparam) {
return myparam.foo.toUpperCase();
}
console.log(myfunction(myobj));
/* Objects */
function MyObject(invar) {
this.myprop = invar;
}
MyObject.prototype.getThing = function () {
return this.myprop;
}
MyObject.prototype.isSubway = function () {
return (this.myprop.toUpperCase() === "SUBWAY");
}
var myo = new MyObject("fooey");
console.log(myo.getThing());
console.log(myo.isSubway());
var otherObject = new MyObject("subway");
if (otherObject.isSubway()) {
console.log("This object is a subway");
}
function Weather(json) {
this.temp = json.temperature;
this.city = json.location;
}
Weather.prototype.isCold = function () {
return (this.temp < 5);
}
var thisWeather = new Weather({
temperature: 10,
location: "Orlando"
});
var thatWeather = new Weather({
temperature: 1,
location: "Toronto"
});
var weatherArr = [thisWeather, thatWeather];
for (var i = 0; i < weatherArr.length; i++) {
if (weatherArr[i].isCold()) {
console.log("It's cold in " + weatherArr[i].city);
} else {
console.log("It's warm in " + weatherArr[i].city);
}
}