Push JSON Objects to array in localStorage

后端 未结 5 1583
别那么骄傲
别那么骄傲 2020-12-01 03:18

I have a function in Javascript:

var a = [];
function SaveDataToLocalStorage(data)
{       
    var receiveddata = JSON.stringify(data);
    a.push(receivedd         


        
5条回答
  •  醉梦人生
    2020-12-01 03:33

    One thing I can suggest you is to extend the storage object to handle objects and arrays.

    LocalStorage can handle only strings so you can achieve that using these methods

    Storage.prototype.setObj = function(key, obj) {
        return this.setItem(key, JSON.stringify(obj))
    }
    Storage.prototype.getObj = function(key) {
        return JSON.parse(this.getItem(key))
    }
    

    Using it every values will be converted to json string on set and parsed on get

提交回复
热议问题