HTML5本地存储JSON多个对象

时间:2012-04-27 08:25:13

标签: javascript html5 local-storage

有人知道吗,当我在javascript中进行循环时,是否可以在其中创建包含多个对象的本地存储?

目前我的代码看起来像这样:

var albums = '';
var album_list = '';

$.each(data, function(i,item){
   var name = item.name;
   albums += '<li>'+item.name+'</li>';

   var album_content = {name: item.name, uid: 1};
   var album_content = album_content+',';

   album_list += album_content;


});

var album_list = '['+album_list+']';   
localStorage.setItem("albums", JSON.stringify(album_list));
var albums_l = JSON.parse(localStorage.getItem("albums"));

$.each(albums_l, function(i,item){
   console.log(item.name);
});

但这给了我一个错误。 任何人都有一个更好的解决方案,所以我只有一个本地存储和所有数据?

2 个答案:

答案 0 :(得分:6)

您在代码中混合对象和字符串。您的album_content在循环中初始化为对象({name: item.name, uid: 1})。在下一行中,您可以通过附加逗号来将其视为字符串。

总体上使用数组来收集所有对象。 (几乎)总是更好地使用本机对象而不是尝试以某种方式模拟它们。

请尝试使用此代码。

var albums = '';
var album_list = [];

$.each(data, function(i,item){
   var name = item.name;
   albums += '<li>'+item.name+'</li>';

   var album_content = {name: item.name, uid: 1};
   // remove that line completly
   // var album_content = album_content+',';

   album_list.push( album_content );

});


localStorage.setItem("albums", JSON.stringify( album_list ));
var albums_l = JSON.parse(localStorage.getItem("albums"));

$.each(albums_l, function(i,item){
   console.log(item.name);
});

答案 1 :(得分:1)

出了什么问题:

var albums = '';
var album_list = '';

$.each(data, function(i,item){
   var name = item.name;
   albums += '<li>'+item.name+'</li>';

   var album_content = {name: item.name, uid: 1};

   // at this point album_content is an object.. so it will be this string afterwards: "[object Object],"
   var album_content = album_content+',';

   album_list += album_content; //you're adding "[object Object],"


});

// album_list will now look like this: '["[object Object],[object Object],"]'
var album_list = '['+album_list+']';
localStorage.setItem("albums", JSON.stringify(album_list));
var albums_l = JSON.parse(localStorage.getItem("albums"));

$.each(albums_l, function(i,item){
   console.log(item.name);
});

如何纠正:

var albums = '';
var album_list = [];

$.each(data, function(i,item){
   var name = item.name;
   albums += '<li>'+item.name+'</li>';

   var album_content = {name: item.name, uid: 1};

   album_list.push(album_content);


});

localStorage.setItem("albums", JSON.stringify(album_list));
var albums_l = $.parseJSON(localStorage.getItem("albums"));

$.each(albums_l, function(i,item){
   console.log(item.name);
});