gpt4 book ai didi

javascript - 尝试在 Node.js 中遍历 JavaScript 数组?

转载 作者:行者123 更新时间:2023-12-03 08:14:22 24 4
gpt4 key购买 nike

我有一个机器人系统,需要通过一系列用户来联系他们以了解即将发生的事件,并且在尝试递归访问此对象中的每个数组时遇到问题。

数组是

var users=bot.servers[bot.serverFromChannel(data['channelid'])].members;
console.log("wee"+util.inspect(users, {showHidden: false, depth: null}))
bot.sendMessage({
to: data['channelid'],
message: "Hello World",
}, function(response) {
console.log("Alright"+users.length)
for (var i = 0, len = users.length; i < len; i++) {
bot.editMessage({
channel: data['channelid'],
messageID: response.id,
message: "Hello <@"+users[i].user.id+">"
});
console.log("wee"+util.inspect(users[i], {showHidden: false, depth: null}))
};
/*bot.deleteMessage({
channel: data['channelid'],
messageID: response.id
});*/
});

到目前为止,它已经完成,发布了数组表并发布了“Hello World”,但停止在“好吧”,未定义。

数组表是这样的

{
"domain": null,
"_events": {},
"_eventsCount": 6,
"connected": true,
"servers": {
"923946464": {
"voice_states": [],
"roles": {
"92394097364": {
"position": -1,
"permissions": 369089,
"name": "@everyone",
"managed": false,
"id": "92394464",
"hoist": false,
"color": 0
}
},
"region": "us-east",
"presences": [
],
"owner_id": "9236892256",
"name": "Group",
"members": {
"92368969305952256": {
"user": {
"username": "Nickoplier",
"id": "9256",
"discriminator": "6",
"avatar": "b37f9a293e509"
},
"roles": [],
"mute": false,
"joined_at": "2000-01-01T01:01:09.497000+00:00",
"deaf": false,
"status": "online",
"game_id": null
},
}
}
}
}

最佳答案

members 是一个对象,而不是数组。使用 Object.keys 获取键数组。

Object.keys(users).forEach(function(key) {
var user = users[key];
// Do stuff to user
});

如果您所在的环境不支持 Object.keys,请添加 es5-shim或使用以下内容:

for (var key in users) {
if (users.hasOwnProperty(key)) {
var user = users[key];
// Do stuff to user
}
}

关于javascript - 尝试在 Node.js 中遍历 JavaScript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34013492/

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