Practice Set - localStorage
for CSCI E3, Harvard University author(s): Larry Bouthillier
by DustyWhite
HTML
<p>There is one part to this practice problem. This exercise is designed to get you comfortable with using <code>window.localStorage</code>, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage" target="_blank">Storage object</a>, and the utilities of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify" target="_blank">JSON object</a>.</p>
<ol>
<li>On lines 11-12, the <code>personInfo</code> object is being converted into a string using JSON.stringify(), and assigned to localStorage. Your task is to do the opposite: retrieve the string from localStorage (Storage.getItem() may help), and output it to the page using the logMessage() function that's provided.
</li>
<p><b>Output:</b>
</p>
<div id="output"></div>
CSS
#output {
border:1px solid black;
padding: .5em;
}
JavaScript
// Initialize our personInfo Object
var personInfo = {
fname: "Bill",
lname: "Adama",
addr: "Galactica CIC",
email: "N/A",
title: "Admiral",
}
// Write the object to localStorage
var jsonPerson = JSON.stringify(personInfo);
window.localStorage.setItem("person", jsonPerson);
// Insert your code below to read the object back from localStorage,
// convert it back to an object,
// and iterate over its properties, printing the property names and their
// values using the logMessage() function. This last part should be
// identical to code you wrote for the previous pratice set
// Utility function for logging convenience
// Logs msg to the element with given id
// If id is undefined, logs to #output
//DS *** My code begins here: ***
window.localStorage.getItem("person");
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();
//DS *** END my code ***