【问题标题】:Using localStorage/sessionStorage to store arrays使用 localStorage/sessionStorage 存储数组
【发布时间】:2019-06-25 17:34:22
【问题描述】:

我正在尝试在 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

【问题讨论】:

标签: javascript html local-storage session-storage


【解决方案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])

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      【解决方案3】:

      可以解析json

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

      或者你可以用','分割得到0th索引项。

      localStorage.getItem('foo').split(',')[0]
      

      【讨论】:

        猜你喜欢
        • 2012-01-27
        • 2017-03-06
        • 1970-01-01
        • 1970-01-01
        • 2011-03-21
        • 2017-10-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多