Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - How to increment a value at localStorage

I have some values that are dynamically stored at localStorage with incremented values like this: localStorage["Value0"], localStorage["Value1"],....

When I try to access them like this:

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 i's value is "01" not 1 ... Is there a way to increment the i's value correctly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

LocalStorage can only store string values. You can use parseInt which converts a string into 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 to include the library:

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

Set a new storage:

var numbers = new Store("numbers")

Put things into it:

numbers.set('num', 2)

Get the value and do anything you want with it:

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

And you can also go crazy and use some arrays:

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

And change things inside it:

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

No type conversion needed. You can also store objects, booleans and other stuff. Just don't forget to save things back in the storage since it doesn't automatically do it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...