How to store array in localStorage Object in html5?

This question already has an answer here:

  • Storing Objects in HTML5 localStorage 25 answers

  • localStorage is for key : value pairs, so what you'd probably want to do is JSON.stringify the array and store the string in the mycars key and then you can pull it back out and JSON.parse it. For example,

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

    Check his Link

    http://diveintohtml5.info/storage.html

    This is like a crash course for working with local storage also check this article from Mozilla Firefox

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

    here is the official documentation for local storage

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

    Just For your problem, you can do it like this

    localStorage only supports strings. Use JSON.stringify() and JSON.parse().

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

    LocalStorage can store strings and not arrays directly. Use some special symbol like '~' to concatenate the elements of array and save it as an array. When retrieving , using split('~') to get back the array.

    链接地址: http://www.djcxy.com/p/27930.html

    上一篇: 检查不为空不与localStorage一起工作

    下一篇: 如何将数组存储在html5的localStorage对象中?