gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:33:23 26 4
gpt4 key购买 nike

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

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

如何创建这个对象或列表?

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

最佳答案

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

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);
}
}
}

关于javascript - 如何创建和读取 javascript 对象以保存以下数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8961503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com