使用localStorage / sessionStorage存储阵列

时间:2019-02-01 06:59:17

标签: javascript html local-storage session-storage

我正在尝试将数组保存在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

3 个答案:

答案 0 :(得分:1)

localStorage只能以其值存储字符串,这就是为什么它仅存储15;

使用JSON.stringify并将其作为localStorage.setItem("foo",JSON.stringify([15,"bye"]))存储在本地存储中;

如果要检索值,请执行JSON.parse(localStorage.getItem("foo"));

答案 1 :(得分:0)

我将使用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])

答案 2 :(得分:0)

您可以解析json

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

或者您可以将','分开,并获得0th索引项目。

localStorage.getItem('foo').split(',')[0]
相关问题