javascript 如何增加 localStorage 的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11375433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:57:58  来源:igfitidea点击:

How to increment a value at localStorage

javascripthtmllocal-storage

提问by Sana Joseph

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

我有一些动态存储在 localStorage 中的值,这些值具有如下递增值: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];

The i's value is "01" not 1 ... Is there a way to increment the i's value correctly?

i 的值是“01”而不是 1 ......有没有办法正确增加 i 的值?

回答by Wern Ancheta

LocalStorage can only store string values. You can use parseInt which converts a string into an integer:

LocalStorage 只能存储字符串值。您可以使用 parseInt 将字符串转换为整数:

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:

您还可以使用 store.js 之类的库来自动为您做事。您所要做的就是包含库:

<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.

不需要类型转换。您还可以存储对象、布尔值和其他东西。只是不要忘记将内容保存回存储中,因为它不会自动执行此操作。

回答by Rob W

To fix the problem of getting 01, simply convert the variable to a number:

要解决 get 的问题01,只需将变量转换为数字:

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

If you want an incremental key name, the following code can also be used (provided that you don't delete keys in between):

如果你想要一个增量键名,也可以使用下面的代码(前提是你不要删除中间的键):

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