How to increment a value at localStorage

前端 未结 2 1934
时光说笑
时光说笑 2020-12-07 02:54

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

When I try

2条回答
  •  难免孤独
    2020-12-07 03:24

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

    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);
    

提交回复
热议问题