繁体   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