I was just working on some tests for Local Storage in HTML5. Note I used Safari 6.0.2, as it seems many web-engines handle their methods different.
If I do this:
localStorage.setItem('subTotal', Number(12345)); // I know, it's redundant :)
var varType = typeof localStorage.getItem('subTotal');
alert(varType);
You would now think; It’s a Number!. But no it’s not.. It seems, even with type casting, that HTML5 Local Storage converts all variable types to Strings when inserting them. It’s funny tho, because when using the Development Tools it shows String values between quotes, but not the Numbers. Maybe it’s the Inspector pane that strips the quotes tho.
I already have an old automatic typeCasting function in jQuery, yet I’m always weary of these cases, as 0 and false, can still make a mess of things.
Anyone know if the localStorage.* Library has a setting to maintain the Variable Types?
You should convert them to JSON first:
Then, when retrieving your item, parse the JSON:
Here’s the fiddle: http://jsfiddle.net/hD9dF/
For easier usage, create your own wrapper:
Here’s the fiddle: http://jsfiddle.net/hD9dF/1/