How to increment a value at localStorage

前端 未结 2 1933
时光说笑
时光说笑 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:32

    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:

    
    

    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.

提交回复
热议问题