簡體   English   中英

將對象添加到 localStorage 中的數組

[英]adding objects to array in localStorage

好的,我已經嘗試在這里遵循示例,我知道可能有幾種不同的方法可以將對象添加到 localstorage 中的數組而不是覆蓋它,但我至少找不到其中一種。

得到了這段代碼來將對象存儲在數組中,但它正在覆蓋自己。 誰能告訴我我錯過了什么? (而且我擔心我可能會錯過很多)。

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:

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

這是一個演示上述內容的小提琴

也許您只需要在推送新條目之前獲取條目:

var allEntries = JSON.parse(localStorage.getItem("allEntries")) || [];
allEntries.push(entry); 
//etc...

將對象添加到 localStorage (Ionic) 中的數組:

var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
if(existingEntries == null) existingEntries = [];
var testObject ={username:this.username, 
mobile:this.mobile,
email:this.email,
type:this.type,
password:this.password};

localStorage.setItem('testObject', JSON.stringify(testObject));
existingEntries.push(testObject);
localStorage.setItem("allEntries", JSON.stringify(existingEntries));

 const object = { name: 'ayyan', age: 29, number: 03070084689, }; const arr = JSON.parse(localstorage.getItem('key_name')) || []; arr.push(object); localstorage.setitem(json.strigify('key_name', arr);

HTML5 localStorage 允許您存儲數據的鍵/值對。 key 和 value 都需要是 string 要將數組存儲為鍵或值,您需要將數組編碼為 JSON 字符串。 在檢索時,您需要將其解碼回數組。

const object = {
name: 'ayyan',
age: 29,
number: 03070084689,
};
const arr = JSON.parse(localstorage.getItem('key_name')) || [];
const data = [arr, ...[object]];
localstorage.setitem(json.strigify('key', data);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM