Add/Append item into localstorage/web storage?

自古美人都是妖i 提交于 2019-12-22 01:07:39

问题


I know localstorage is just a simple hash map with getItem and setItem. What if my Item is a JSON array and I would just like to add one item at the end of the array? Are there more efficient ways than calling setItem for just one more entry?


回答1:


Unfortunately no.

localStorage support only the string type so you will have to JSON.stringify the array before saving, which means you need to load it and parse it before you can add anything to it.

You can write a simple wrapper to do this (can support various types):

function appendItem(key, data) {

    var t = data.constructor, tmp;

    switch(t) {

         case Array:
             tmp = localStorage.getItem(key);
             tmp = (tmp === null) ? [] : JSON.parse(tmp);
             tmp.push(data);

             localStorage.setItem(key, JSON.stringify(tmp));
             break;

         case String:
             //... and so forth
    }
}

(error and same type checking must also be implemented in this approach).

Optionally you can use a delayed writing approach so you can fill the array more efficiently (burst writing) and only when needed the data is updated to localStorage. Here you can initially load the existing array and then update it when data is added to it.

You can bake this into an object for each array, but for simplicity:

var a = []; //load existing array at init
var timer;
var key = 'myArray';

//append data to array and re-start timer
function appendArray(item) {

    clearTimeout(timer);
    a.push(item);

    timer = setTimout(writeData, 2000); //wait 2 seconds to write last append(s)
}

//write the data if dirty
function writeData() {
    localStorage.setItem(key, JSON.stringify(a));
}

For security you can subscribe to the window.onunload event to do a final write when user navigates away from current page.



来源:https://stackoverflow.com/questions/17356625/add-append-item-into-localstorage-web-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!