最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Problems create multidimensional array in localstorage - Stack Overflow

programmeradmin0浏览0评论

I'm trying to save some data in localstorage. My script looks like this:

    localStorage.clear(); //only for testing

    if(typeof localStorage.akten == "undefined") {
        localStorage.akten = new Array();
    }

    var nam = "alpha";


    localStorage.akten[nam] = {
        "beta": 12
    };

    localStorage["a_akte"] = nam;

But if I do console.log(localStorage); or console.log(localStorage.akten); akten is only an empty string? Why? With an normal object instead of localStorage it works well.

I'm trying to save some data in localstorage. My script looks like this:

    localStorage.clear(); //only for testing

    if(typeof localStorage.akten == "undefined") {
        localStorage.akten = new Array();
    }

    var nam = "alpha";


    localStorage.akten[nam] = {
        "beta": 12
    };

    localStorage["a_akte"] = nam;

But if I do console.log(localStorage); or console.log(localStorage.akten); akten is only an empty string? Why? With an normal object instead of localStorage it works well.

Share Improve this question asked Sep 5, 2013 at 14:09 idmeanidmean 14.9k9 gold badges61 silver badges89 bronze badges 1
  • JavaScript Array accepts only numerical indices. When you convert your array to JSON, the serialization will not include your arbitrary named properties (e.g. alpha). You should use an Object instead. And you can use literals (e.g. {} for Object and [] for Array). – eyelidlessness Commented Sep 5, 2013 at 14:13
Add a ment  | 

2 Answers 2

Reset to default 5

Suprisingly the devil is in the details. localStorage only stores strings. Encode your objects as JSON before depositing them there using for example JSON.stringify() and JSON.parse().

This is because localStorage is not an Object; it's an interface. You can only assign a String to it, and the best way to do so is with localStorage.setItem. If you want to be setting more plex data, you'll need to encode it as JSON first.

function localStore(key, obj) {
    return window.localStorage.setItem(key, JSON.stringify(obj));
}

function localGet(key) {
    return JSON.parse(window.localStorage.getItem(key));
}

localStore('foo', {bar: 'baz'});
localGet('foo'); // Object {bar: "baz"}
发布评论

评论列表(0)

  1. 暂无评论