Is it possible to store integer value in localStorage like in Javascript objects and extract it without typecasting?

こ雲淡風輕ζ 提交于 2019-12-18 03:10:49

问题


When I assign integer value to localStorage item

localStorage.setItem('a',1)

and check its type

typeof(localStorage.a)
"string"

it returns string, I can typecast it to int for my use

parseInt(localStorage.a)

My question is it possible to store integer value inside localStorage as I can do for Javascript objects without typecasting?

a={};
a.number=1;
typeof(a.number)
"number"

回答1:


My question is it possible to store integer value inside localStorage as I can do for Javascript objects without typecasting?

No.

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys can be strings or integers, but the values are always strings. [source]




回答2:


Actually you can, if we agree that parsing is not the same as typecasting :

let val = 42;
localStorage.answer = JSON.stringify(val);
let saved = JSON.parse(localStorage.answer);
console.log( saved === val ); // true

Fiddle since over-protected stacksnippets don't allow localStorage.

For simplicity, you should anyway always stringify to JSON what you are saving in localStorage, this way you don't have to think about what you are saving / retrieving, and you will avoid "[object Object]" being saved.



来源:https://stackoverflow.com/questions/33952287/is-it-possible-to-store-integer-value-in-localstorage-like-in-javascript-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!