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

前端 未结 2 912
情深已故
情深已故 2020-12-03 07:19

When I assign integer value to localStorage item

localStorage.setItem(\'a\',1)

and check its type

typeof(localStorage.a)
\         


        
相关标签:
2条回答
  • 2020-12-03 07:58

    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]

    0 讨论(0)
  • 2020-12-03 08:22

    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.

    0 讨论(0)
提交回复
热议问题