How to increase value on localStorage

I have some values โ€‹โ€‹that are dynamically stored in localStorage with these values: localStorage ["Value0"], localStorage ["Value1"], ....

When I try to access them as follows:

JavaScript:

localStorage["Counter"]=0; var i = localStorage["Counter"]; var d =localStorage["Value"+i]; i = i + 1; // i becomes "01" var f = localStorage["Value"+i]; 

The value of i is "01", not 1 ... Is there a way to properly increase the value of i?

+4
source share
2 answers

LocalStorage can only store string values. You can use parseInt, which converts the string to an integer:

 var new_value = parseInt(localStorage.getItem('num')) + 1 

You can also use libraries like store.js to do things automatically for you. All you have to do is enable the library:

 <script src="store.js"></script> 

Install a new repository:

 var numbers = new Store("numbers") 

Put things in it:

 numbers.set('num', 2) 

Get the value and do anything with it:

 numbers.get('num') + 1 //output: 3 

And you can also go crazy and use several arrays:

 numbers.set('nums', [1,2,3]) 

And change things inside it:

 numbers.get('nums')[0] + 3 //output: 4 

No type conversion required. You can also store objects, booleans, and more. Just remember to keep things in storage, as it does not do this automatically.

+15
source

To fix getting 01 , just convert the variable to a number:

 var i = +localStorage.getItem('Counter'); // or +localStorage.Counter; 

If you want to enter an incremental key name, you can use the following code (provided that you do not delete the keys between them):

 var keyname = 'Value' + localStorage.length; localstorage.setItem(keyname, value); 
+2
source

All Articles