在localStorage中向对象添加对象 [英] adding objects to array in localStorage

查看:111
本文介绍了在localStorage中向对象添加对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经尝试过这里的示例了,我知道可能有一些不同的方法在localstorage中向数组添加对象而不是覆盖它但是我没有找到至少其中一个。

Ok, I've tried to follow examples here, I know there might be a few different ways of adding objects to an array in localstorage and not overwriting it but I'm failing to find at least one of them.

得到这个代码来存储数组中的对象但是它会覆盖自己。愿有人告诉我我错过了什么吗? (而且我担心我可能会遗漏很多)。

Got this code to store objects in array but it's overwriting itself. May anyone show me what am I missing? (And I'm afraid I could be missing a lot).

function addEntry() {
    var entryTitle = document.getElementById("entryTitle").value;
    var entryText = document.getElementById("entryText").value;
    var entry = {
        "title": entryTitle,
        "text": entryText
    };
    localStorage.setItem("entry", JSON.stringify(entry));
    var allEntries = [];
    allEntries.push(entry);
    localStorage.setItem("allEntries", JSON.stringify(allEntries));
};


推荐答案

当你使用 setItem 它会覆盖之前的项目。您需要使用 getItem 来检索旧列表,附加到它,然后将其保存回localStorage:

When you use setItem it overwrites the item which was there before it. You need to use getItem to retrieve the old list, append to it, then save it back to localStorage:

function addEntry() {
    // Parse any JSON previously stored in allEntries
    var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
    if(existingEntries == null) existingEntries = [];
    var entryTitle = document.getElementById("entryTitle").value;
    var entryText = document.getElementById("entryText").value;
    var entry = {
        "title": entryTitle,
        "text": entryText
    };
    localStorage.setItem("entry", JSON.stringify(entry));
    // Save allEntries back to local storage
    existingEntries.push(entry);
    localStorage.setItem("allEntries", JSON.stringify(existingEntries));
};

这是小提琴,演示了上述内容。

Here is a fiddle which demonstrates the above.

这篇关于在localStorage中向对象添加对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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