如何在localStorage上增加一个值 [英] How to increment a value at localStorage
问题描述
我有一些动态存储在localStorage的值,像这样递增的值:localStorage [Value0],localStorage [Value1],....
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:
JavaScript:
localStorage["Counter"]=0;
var i = localStorage["Counter"];
var d =localStorage["Value"+i];
i = i + 1; // i becomes "01"
var f = localStorage["Value"+i];
我的值是01而不是1 ...有没有办法增加i的值是否正确?
The i's value is "01" not 1 ... Is there a way to increment the i's value correctly?
推荐答案
LocalStorage只能存储字符串值。您可以使用parseInt将字符串转换为整数:
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
您也可以使用像store.js这样的库为您自动执行操作。您只需包含该库:
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>
设置新的存储空间:
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.
这篇关于如何在localStorage上增加一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!