admin管理员组文章数量:1317731
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.
-
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 anObject
instead. And you can use literals (e.g.{}
forObject
and[]
forArray
). – eyelidlessness Commented Sep 5, 2013 at 14:13
2 Answers
Reset to default 5Suprisingly 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"}
本文标签: javascriptProblems create multidimensional array in localstorageStack Overflow
版权声明:本文标题:javascript - Problems create multidimensional array in localstorage - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742020860a2414646.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论