将localStorage与javascript对象和/或数组和/或对象数组一起使用

时间:2014-08-17 15:10:20

标签: javascript arrays json

我的应用使用数组来存储“朋友”信息:

var friends = new Array();

每个“朋友”项目都有一个名称,颜色和存储为JSON对象的条目列表。

这是我最原始的形式:

friends[0] = '{"name":"Fred","color":"rgb(255, 0, 0)","entries":"[{"time":"xxxx","desc":"Party"},{"time":"yyyy","desc":"Shopping"},{"time":"zzzz","desc":"Dinner"}]}';
friends[1] = '{"name":"George","color":"rgb(0, 255, 0)","entries":"[{"time":"qqqq","desc":"Car Pool"},{"time":"vvvv","desc":"Spa Treatment"},{"time":"wwww","desc":"Shopping"}]}';

编辑:

我也尝试过没有''围绕JSON,就像这样:

friends[0] = {"name":"Fred","color":"rgb(255, 0, 0)","entries":"[{"time":"xxxx","desc":"Party"},{"time":"yyyy","desc":"Shopping"},{"time":"zzzz","desc":"Dinner"}]};
friends[1] = {"name":"George","color":"rgb(0, 255, 0)","entries":"[{"time":"qqqq","desc":"Car Pool"},{"time":"vvvv","desc":"Spa Treatment"},{"time":"wwww","desc":"Shopping"}]};

我可以轻松访问朋友[0] .name,朋友[0] .color等值。

我使用此命令将friends数组存储在localStorage中:

localStorage.setItem( “allFriendInfo”,JSON.stringify(朋友));

在Chrome开发者工具“资源”中检查后,我看到字符串存储为:

[{"name":"Fred","color":"rgb(255, 0, 0)","entries":"[{\"time\":\"xxxx\",\"desc\":\"Party\"},{\"time\":\"yyyy\",\"desc\":\"Shopping\"},{\"time\":\"zzzz\",\"desc\":\"Dinner\"}]"},{"name":"George","color":"rgb(0, 255, 0)","entries":":"[{\"time\":\"qqqq\",\"desc\":\"Car Pool\"},{\"time\":\"vvvv\",\"desc\":\"Spa Treatment\"},{\"time\":\"wwww\",\"desc":\"Shopping\"}]"}]

我从本地存储中读取了JSON.parse:

friends = JSON.parse(localStorage.getItem("allFriendInfo"));

我可以使用“friend [0]”访问存储的数据,该信息在警告中显示如下:

friends[0] = {"name":"Fred","color":"rgb(255, 0, 0)","entries":"[{"time":"xxxx","desc":"Party"},{"time":"yyyy","desc":"Shopping"},{"time":"zzzz","desc":"Dinner"}]"}

alert(friends.length);

返回一个等于数组中项目数的值。

但我无法得到

friends[0].name

返回“name”属性的值,并且无法处理对象中“条目”列表。

编辑:删除引号后,我可以获得朋友[0] .name等值,但我无法从朋友[0] .entries.time或类似的东西中获得任何欢乐。

提前感谢任何可以帮助这位新手的“真正的”程序员。

0 个答案:

没有答案