Push JSON Objects to array in localStorage

后端 未结 5 1590
别那么骄傲
别那么骄傲 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:37

    Putting a whole array into one localStorage entry is very inefficient: the whole thing needs to be re-encoded every time you add something to the array or change one entry.

    An alternative is to use http://rhaboo.org which stores any JS object, however deeply nested, using a separate localStorage entry for each terminal value. Arrays are restored much more faithfully, including non-numeric properties and various types of sparseness, object prototypes/constructors are restored in standard cases and the API is ludicrously simple:

    var store = Rhaboo.persistent('Some name');
    store.write('count', store.count ? store.count+1 : 1);
    
    store.write('somethingfancy', {
      one: ['man', 'went'],
      2: 'mow',
      went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
    });  
    store.somethingfancy.went[1].mow.write(1, 'lawn');
    

    BTW, I wrote it.

提交回复
热议问题