将项目添加/附加到localstorage / web存储中? [英] Add/Append item into localstorage/web storage?

查看:135
本文介绍了将项目添加/附加到localstorage / web存储中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道localstorage只是一个简单的哈希映射,其中包含 getItem setItem 。如果我的Item是JSON数组并且我只想在数组的末尾添加一个项,该怎么办?是否有更有效的方法比再调用 setItem 还要多一个条目?

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?

推荐答案

不幸的是没有。

localStorage 仅支持字符串类型,所以你必须在保存之前JSON.stringify数组,这意味着你需要加载它并解析它,然后才能添加任何东西。

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

您可以选择使用延迟写入方法这样你就可以更有效地填充数组(突发写入),并且只在需要时才将数据更新为 localStorage 。在这里,您可以初始加载现有数组,然后在添加数据时更新它。

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

为了安全起见,您可以订阅 window.onunload 用户导航离开当前页面时进行最终写入的事件。

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

这篇关于将项目添加/附加到localstorage / web存储中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆