3

有谁知道,当我在 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);
});

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

4

2 回答 2

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);
});
于 2012-04-27T08:29:11.433 回答
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);
});
于 2012-04-27T08:31:02.183 回答