Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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" 
like image 222
nickalchemist Avatar asked Nov 27 '15 07:11

nickalchemist


People also ask

Can we store JavaScript objects directly into localStorage?

In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON. parse method.

What method allows you to retrieve the value of an object in localStorage?

To get items from localStorage, use the getItem() method. getItem() allows you to access the data stored in the browser's localStorage object.

How can we store JavaScript arrays and objects in localStorage or sessionStorage?

Use localStorage. setObj(key, value) to save an array or object and localStorage. getObj(key) to retrieve it. The same methods work with the sessionStorage object.


2 Answers

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]

like image 189
Adam Zerner Avatar answered Sep 17 '22 15:09

Adam Zerner


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.

like image 29
Kaiido Avatar answered Sep 20 '22 15:09

Kaiido