HTML and CSS Reference
In-Depth Information
alert("Without conversion Sum = " + sum1 + "\r\n" +
"With conversion Sum = " + sum2);
});
As you can see, two numbers are stored in localStorage with the keys number1 and number2 ,
respectively. Notice that this time, instead of using setItem() and getItem() , the code uses a familiar
dictionary-access syntax to store the items. The sum1 variable stores the sum of the values of these two keys
without performing any conversion, whereas sum2 stores their sum by first converting them to numbers
using the Number() function. An alert box displays the values of sum1 and sum2 , as shown in Figure 7-2.
Figure 7-2. Adding numeric values after conversion
Figure 7-2 confirms that localStorage stores data in plain-text format and you need to convert it to an
appropriate data format before using it in further processing.
Storing date values is similar to storing numbers in that you need to convert date strings into
JavaScript Date objects. Listing 7-3 shows how this can be done.
Listing 7-3. Storing Dates in localStorage
$(document).ready(function () {
var storage = window.localStorage;
storage["date"] = new Date(2012,5,15);
var date1 = storage["date"];
try{
alert("Without conversion Year = " + date1.getFullYear());
}
catch(e){
alert("Data is not of date type!");
}
var date2 = new Date(storage["date"]));
try {
alert("With conversion Year = " + date2.getFullYear());
}
catch (e) {
 
Search WWH ::




Custom Search