gpt4 book ai didi

javascript - 使用 localStorage/sessionStorage 存储数组

转载 作者:行者123 更新时间:2023-11-27 22:57:48 25 4
gpt4 key购买 nike

我试图在 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])

关于javascript - 使用 localStorage/sessionStorage 存储数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com