使用JSON.parse()检索本地存储阵列列表

时间:2015-05-30 03:14:53

标签: javascript jquery json local-storage

我想循环遍历保存的localstorage的每个数组,但是使用此代码

localStorage.setItem("fav", JSON.stringify(merchant));

                var savedMerchant = JSON.parse(localStorage.getItem("fav"));

                $.each(savedMerchant,function(){
                    console.log(this);

                });

为什么得到这个?

String {0: "L", length: 1, [[PrimitiveValue]]: "L"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "z", length: 1, [[PrimitiveValue]]: "z"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "d", length: 1, [[PrimitiveValue]]: "d"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "Z", length: 1, [[PrimitiveValue]]: "Z"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
VM420:210 String {0: "l", length: 1, [[PrimitiveValue]]: "l"}
VM420:210 String {0: "o", length: 1, [[PrimitiveValue]]: "o"}
VM420:210 String {0: "r", length: 1, [[PrimitiveValue]]: "r"}
VM420:210 String {0: "a", length: 1, [[PrimitiveValue]]: "a"}

1 个答案:

答案 0 :(得分:1)

TL; DR

  1. 使用JSON.parse()localStorage
  2. 确保序列化/反序列化
  3. 在写入JSON.parse()
  4. 之前,确保type为数组并进行编码

    以下localStorage["fav"]声明表示var savedMerchant = JSON.parse(localStorage.getItem("fav")); // access to localStorage using getItem() corrected from // @Seth McClaine in comments to question. Good spot! 使用JSON.stringify()编码为JSON:

    object

    因此,在写入typeof(x) === 'object'之前,请确保您编码的类型localStorage使用NSApplicationx.isArray()进行验证或调试。

    希望这会有所帮助。

相关问题