簡體   English   中英

使用 localStorage/sessionStorage 存儲數組

[英]Using localStorage/sessionStorage to store arrays

我正在嘗試在 localStorage 值中保存一個數組。 我只能訪問值的字符,而不能訪問分組值。 我一直在嘗試編寫一個函數來用逗號對它們進行分組,但我不知道如何正確地做到這一點。

// setting values
localStorage.setItem("foo", [15,"bye"]);

// writes the whole thing.
document.write(localStorage.getItem("foo")); // returns 15,bye

// only writes the first character, instead of one part of the array 
// (in this case it would be 15).
document.write(localStorage.getItem("foo")[0]); // returns 1

我會使用JSON.stringify來設置數據和JSON.parse來獲取存儲的數據。

嘗試這個:

localStorage.setItem("foo", JSON.stringify([15,"bye"]));

// writes the whole thing.
localStorage.getItem("foo"); // returns 15,bye

var data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])

localStorage只能在其值中存儲字符串,這就是為什么它只存儲 15;

使用JSON.stringify並將其作為localStorage.setItem("foo",JSON.stringify([15,"bye"]))存儲在本地存儲中;

如果要檢索該值,請執行JSON.parse(localStorage.getItem("foo"));

你可以解析json

let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])

或者您可以按 ',' 拆分並獲得第0th索引項。

localStorage.getItem('foo').split(',')[0]

暫無
暫無

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

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