How do I store an array in localStorage?

This question already has an answer here:

  • Storing Objects in HTML5 localStorage 25 answers

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

    var names = [];
    names[0] = prompt("New member name?");
    localStorage.setItem("names", JSON.stringify(names));
    
    //...
    var storedNames = JSON.parse(localStorage.getItem("names"));
    

    The localStorage and sessionStorage can only handle strings. You can extend the default storage-objects to handle arrays and objects. Just include this script and use the new methods:

    Storage.prototype.setObj = function(key, obj) {
        return this.setItem(key, JSON.stringify(obj))
    }
    Storage.prototype.getObj = function(key) {
        return JSON.parse(this.getItem(key))
    }
    

    Use localStorage.setObj(key, value) to save an array or object and localStorage.getObj(key) to retrieve it. The same methods work with the sessionStorage object.

    If you just use the new methods to access the storage, every value will be converted to a JSON-string before saving and parsed before it is returned by the getter.

    Source: http://www.acetous.de/p/152


    Use JSON.stringify() and JSON.parse() as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (eg member name three|||bars ).

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

    上一篇: 在javascript中清除localStorage?

    下一篇: 如何将数组存储在localStorage中?