![](/img/trans.png)
[英]Performance issues with using 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.