如何创建和读取javascript对象以保存以下数据结构?

时间:2012-01-22 13:44:21

标签: javascript

我需要创建以下数据结构:

userid, onlinetime, offlinetime

我需要在列表中重复用户ID。

这样的事情:

userid: 1, onlinetime: 11:10:30, offlinetime: 11:18:12
userid: 1, onlinetime: 11:14:14, offlinetime: 11:52:41
userid: 2, onlinetime: 8:08:14, offlinetime: 1:15:00

如何创建此对象或列表?

如何阅读此对象或列表? (我需要比较在线和离线时间。)

1 个答案:

答案 0 :(得分:2)

您可以使用userId和connectionTimes属性创建User对象,并将它们添加到用户数组中,如下所示:

function createUsers()
{
    var users = [];

    users[0] = {
        userId: 1,
        connectionTimes:
            [
                {onlineTime:"11:10:30", offlineTime:"11:18:12"},
                {onlineTime:"11:14:14", offlineTime:"11:52:41"}
            ]
    }

    users[1] = {
        userId: 2,
        connectionTimes: 
            [
                {onlineTime:"8:08:14", offlineTime:"1:15:00"}
            ]
    }   

    return users;
}

拥有一组用户后,您可以通过比较userId属性来迭代它并查找用户:

var users = createUsers();

for (var i=0;i<users.length;i++)
{
    if (users[i].userId === 2)
    {
        for (var j=0;j<users[i].connectionTimes.length;j++)
        {
            alert("onlineTime: " + users[i].connectionTimes[j].onlineTime + ", " + "offlineTime: " + users[i].connectionTimes[j].offlineTime);
        }   
    }
}

修改

这是基于createUser和getConnectionTime函数的代码的分解版本:

function getConnectionTime(onTime, offTime)
{
    return {onlineTime: onTime, offlineTime: offTime};
}

function createUser(uid, connTimes)
{
    return {userId: uid, connectionTimes: connTimes};
}

var users = [];

var connTimes = [];
connTimes.push(getConnectionTime("11:10:30", "11:18:12"));
connTimes.push(getConnectionTime("11:14:14", "11:52:41"));
users.push(createUser(1, connTimes));

connTimes = [];
connTimes.push(getConnectionTime("8:08:14", "1:15:00"));
users.push(createUser(2, connTimes));

for (var i=0;i<users.length;i++)
{
    if (users[i].userId === 2)
    {
        for (var j=0;j<users[i].connectionTimes.length;j++)
        {
            alert("onlineTime: " + users[i].connectionTimes[j].onlineTime + ", " + "offlineTime: " + users[i].connectionTimes[j].offlineTime);
        }   
    }
}