[英]Using localStorage/sessionStorage to store arrays
I am trying to save an array inside of a localStorage value.我正在尝试在 localStorage 值中保存一个数组。 I can only access chars of the value, not the grouped value.
我只能访问值的字符,而不能访问分组值。 I have been trying to write a function to group them by commas, but I can't figure out how to do it correctly.
我一直在尝试编写一个函数来用逗号对它们进行分组,但我不知道如何正确地做到这一点。
// 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
I would use JSON.stringify
to set the data and JSON.parse
to fetch the stored data.我会使用
JSON.stringify
来设置数据和JSON.parse
来获取存储的数据。
Try this:尝试这个:
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
can only store string in its value, that is why it is storing only 15; localStorage
只能在其值中存储字符串,这就是为什么它只存储 15;
Use JSON.stringify
and store it in the local storage as localStorage.setItem("foo",JSON.stringify([15,"bye"]))
;使用
JSON.stringify
并将其作为localStorage.setItem("foo",JSON.stringify([15,"bye"]))
存储在本地存储中;
If you want to retrieve the value do as JSON.parse(localStorage.getItem("foo"));
如果要检索该值,请执行
JSON.parse(localStorage.getItem("foo"));
You can parse json你可以解析json
let data = JSON.parse(localStorage.getItem("foo"));
console.log(data[0])
Or you can split by ',' and get the 0th
index item.或者您可以按 ',' 拆分并获得第
0th
索引项。
localStorage.getItem('foo').split(',')[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.