- The First program
- Javascript ft. variables
- Javascript functions
- Javascript Types
- Javascript Object/Class
- Javascript Array of Objects
- Javascript Table
console.log("hello world!")
var msg = "How are you today?";
console.log(msg);
function logMsg(output){
console.log(output);
}
logMsg(msg);
logMsg("I'm doing ok");
logMsg(2020);
function logItType(output){
console.log(typeof output+":", output);
}
console.log("Looking at dynamic nature of types in JavaScript")
logItType("hello"); // String
logItType(2020); // Number
logItType([1, 2, 3]); // Object is generic for this Array, which similar to Python List
function Item(name,atk,price,description){
this.name = name;
this.atk=atk;
this.price = price;
this.description = description;
this.equipped = false;
}
Item.prototype.toggleEquiped = function(){
this.equipped=true;
}
Item.prototype.toJSON = function(){
const obj = {name: this.name, atk: this.atk, price: this.price, description: this.description, equipped: this.equipped};
const json = JSON.stringify(obj);
return json;
}
Item.prototype.logItem=function(){
console.log(this.name);
console.log("Atk:",this.atk);
console.log("Price:",this.price);
console.log('"'+this.description+'"');
if (this.selected=true){
console.log("This item is equipped!")
}
console.log("\n");
}
var coolSword=new Item("Cool Sword",999,9999,"A very cool sword");
coolSword.toggleEquiped();
logItType(coolSword+"\n");
logItType(coolSword.toJSON()+"\n");
coolSword.logItem();
var Inventory = [
new Item("Beginner's Blade",10,5,"A weapon fit for a beginner"),
new Item("Adventurer's Blade",20,10,"A weapon that signifies experiences in adventure"),
new Item("The Frost Edge",50,150,"The treasured sword of Frostpeak"),
coolSword
];
for (let i = 0; i < Inventory.length; i++){
Inventory[i].logItem();
}
var style = (
"display:inline-block;" +
"background:black;" +
"border: 2px solid grey;" +
"box-shadow: 0.8em 0.4em 0.4em grey;"
);
// HTML Body of Table is build as a series of concatenations (+=)
var body = "";
// Heading for Array Columns
body += "<tr>";
body += "<th><mark>" + "Name" + "</mark></th>";
body += "<th><mark>" + "Attack" + "</mark></th>";
body += "<th><mark>" + "Price" + "</mark></th>";
body += "<th><mark>" + "Description" + "</mark></th>";
body += "</tr>";
// Data of Array, iterate through each row of compsci.classroom
for (var item of Inventory) {
// tr for each row, a new line
body += "<tr>";
// td for each column of data
body += "<td>" + item.name + "</td>";
body += "<td>" + item.atk + "</td>";
body += "<td>" + item.price + "</td>";
body += "<td>" + item.description + "</td>";
// tr to end line
body += "<tr>";
}
htmlFrag="<div style='" + style + "'>" +
"<table>" +
body +
"</table>" +
"</div>"
$$.html(htmlFrag);