Practice Set - Object Literals and Iterating Over an Bbject
for CSCI E3, Harvard University author(s): Larry Bouthillier
by DustyWhite
HTML
<p>This practice problem is designed to help make you comfortable with working with an object's properties - creating them, referencing them, and iterating over them. There are two parts to this practice problem.</p>
<ol>
<li>Add two keys and values to this object. You can make them anything you like: title, shoe size, height and weight...whatever. You may also change the values provided if you prefer, so that this object describes anyone you like.</li>
<li>Add code to this example that will iterate over this object's properties and write each property name and its value using the logMessage() function provided. Remember that in the lesson, we talked about the <br/><code>for (key in object){}</code> looping technique. </li>
</ol>
<p><b>Output:</b></p>
<div id="output"></div>
CSS
#output {
border:1px solid black;
padding: .5em;
}
JavaScript
// Initialize our personInfo Object
var personInfo = {
lname: "Kitty", //DS NOTE: I purposefully transposed fname &
fname: "Hello", //DS lname (European style) to make HK sound more ominous
occupation: "Loveable tyrant",
goal: "Global domination",
creator: "Sanrio Corporation",
prmryWeapon: "Cuteness"
}
// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
function logMessage(msg, id) {
var msg = ""; //DS I had to add this as the starting code threw UNDEFINED errors! *** >:-( !!! ***
var data;
for (data in personInfo) {
msg += personInfo[data] + "; ";
}
if (!id) {
id = "output";
}
document.getElementById(id).innerHTML += msg + "<br>";
}
logMessage();