【问题标题】:How to store array in localStorage Object in html5? [duplicate]如何将数组存储在 html5 中的 localStorage 对象中? [复制]
【发布时间】:2013-10-11 01:21:25
【问题描述】:

如何在html5的localStorage对象中存储mycars数组?

var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

localStorage.mycars=?;

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    localStorage 用于key : value 对,所以您可能想要做的是JSON.stringify 数组并将字符串存储在mycars 键中,然后您可以将其拉回JSON.parse它。例如,

    var mycars = new Array();
    mycars[0] = "Saab";
    mycars[1] = "Volvo";
    mycars[2] = "BMW";
    
    localStorage["mycars"] = JSON.stringify(mycars);
    
    var cars = JSON.parse(localStorage["mycars"]);
    

    【讨论】:

      【解决方案2】:

      查看他的链接

      http://diveintohtml5.info/storage.html

      这就像一个使用本地存储的速成课程,也可以查看来自 Mozilla Firefox 的这篇文章

      http://hacks.mozilla.org/2009/06/localstorage/

      这里是本地存储的官方文档

      http://dev.w3.org/html5/webstorage/

      只是为了你的问题,你可以这样做

      localStorage 仅支持字符串。使用JSON.stringify()JSON.parse().

      var mycars = [];
      localStorage["mycars"] = JSON.stringify(carnames);
      var storedNames = JSON.parse(localStorage["mycars"]);
      

      【讨论】:

        【解决方案3】:

        LocalStorage 可以直接存储字符串而不是数组。使用像 '~' 这样的特殊符号来连接数组的元素并将其保存为数组。检索时,使用 split('~') 取回数组。

        【讨论】:

        • 我很想看到更多关于这个概念@ParagGangil
        猜你喜欢
        • 2011-03-06
        • 1970-01-01
        相关资源
        最近更新 更多