我有这个JSON对象,如下所示。
$scope.members =
[{
id: "member_0",
json: {
name: $cookieStore.get("member_0_name"),
class: $cookieStore.get("member_0_class"),
items: {
fooItem: $cookieStore.get("member_0_items_fooItem")
}
}
},
{
id: "member_1",
json: {
name: $cookieStore.get("member_1_name"),
class: $cookieStore.get("member_1_class"),
items: {
fooItem: $cookieStore.get("member_1_items_fooItem")
}
}
}];
现在,我想改进代码,以便可以使用给定的数字创建一定数量的JSON对象。我希望下面的代码看起来像伪,但无法解决。
var num_of_members = 5;
for (var i = 0; i < num_of_members; i++) {
$scope.members =
[{
id: "member_"+[i],
json: {
name: $cookieStore.get("member_"+[i]+"_name"),
class: $cookieStore.get("member_"+[i]+"_class"),
items: {
fooItem: $cookieStore.get("member_"+[i]+"_items_fooItem")
}
}
}];
}
答案 0 :(得分:1)
我认为此代码可以帮助您:
var num_of_members = 5;
$scope.members = [];
for (var i = 0; i < num_of_members; i++) {
var member = {
id: "member_"+[i],
json: {
name: $cookieStore.get("member_"+[i]+"name"),
class: $cookieStore.get("member_"+[i]+"class"),
items: {
fooItem: $cookieStore.get("member_"+[i]+"_items_fooItem")
}
}
};
$scope.members.push(member);
}
只需为每个id创建一个新成员,然后将其推送到成员数组中。