1.第一种数据结构:
activities = [
{
name: "first activity",
sign_ups: [],
bids: []
},
{
name: "first activity",
sign_ups: [
{
name: "仝键",
phone: "13600000000"
},
{
name: "于硕",
phone: "15600000000"
}
],
bids: [
{
name: "竞价1",
biddings: [
{
name: "仝键",
phone: "13600000000",
price: "12"
},
{
name: "于硕",
phone: "15600000000",
price: "10"
}
]
}
]
}
];
这种数据结构所有的信息都存储在一个数组里,而每个活动又存储了name,sign_ups,bids,sign_ups和bids又分别存储活动报名和竞价信息.结构非常清晰,要取某一数据也很好取.但要存储或修改数据时由于嵌套比较多,所以步骤比较麻烦.以存储竞价信息为例:
Bidding.prototype.save_bidding = function () {
var bidding = this;
var activities = Activity.get_activities();
_.map(activities, function (activity) {
if (activity.name == Activity.get_active_activity_name()) {
_.map(activity.bids, function (bid) {
if (bid.name == Bid.get_current_bid()) {
bid.biddings.push(bidding)
}
})
}
})
localStorage.setItem("activities", JSON.stringify(activities));
}
2.第二种数据结构:
activities = {
"0": {
name: "first activity",
sign_ups: [],
bids: [],
biddings: {}
},
"1": {
name: "second activity",
sign_ups: [
{
name: "仝键",
phone: "13600000000"
},
{
name: "于硕",
phone: "15600000000"
}
],
bids: ["竞价1", "竞价2"],
biddings: {
"竞价1": [
{
phone: "13600000000",
price: "12"
},
{
phone: "15600000000",
price: "10"
}
],
"竞价2": [
{
phone: "13600000000",
price: "10"
},
{
phone: "15600000000",
price: "12"
},
]
}
]
};
这种数据结构所有的信息都存储在一个hash表里,每个活动都对应一个key,其value又包括name,sign_ups,bids,biddings,结构也比较清楚.相对于第一种结构,他把竞价名称抽成一个数组存储起来,用起来更加方便.修改数据时,找到相对应的key,修改它的key就行.以存储竞价信息为例:
Bidding.prototype.save_bidding = function () {
var bidding = this;
var bid = Activity.get_current_bid();
var activities = Activity.get_activities();
_.map(activities, function (value, key) {
if (key == Activity.get_current_activity()) {
value.biddings[bid].push(bidding);
}
})
localStorage.setItem("activities", JSON.stringify(activities));
}
3.第三种数据结构:
activities = [
{
id: "0",
name: "first activity"
},
{
id: "1",
name: "second activity"
}
];
sign_ups = [
{
name: "仝键",
phone: "13600000000",
activity_id: "0"
},
{
name: "于硕",
phone: "15600000000",
activity_id: "0"
}
]
bids = [
{
name: "竞价1",
activity_name: "0",
biddings: [
{
phone: "13600000000",
price: "9"
},
{
phone: "15600000000",
price: "10"
}
]
}
];
这种数据结构把活动名称(activities),报名信息(sign_ups),竞价信息(bids)分开存储,结构不太清晰.取数据时不太方便,但是嵌套较少,修改或存储数据时特别方便,以保存竞价信息为例:
Bid.create_new_bid = function (activity_id) {
var bids = Bid.get_bids();
var bid = new Bid(activity_id);
bids.push(bid);
localStorage.setItem("bids", JSON.stringify(bids));
}
总之,三种数据结构各有优劣,从第一种到第三种数据结构扩展性越来越好,存储数据比较方便;结构变的不太清晰,取数据不太方便.第一种是要一层一层的取,第三种是要筛选出满足特定条件的值(此处必须小心找出所有要满足的条件).