我有(可能是一个非常简单的)问题:
我一直在用
client.guilds.cache.map((guild) => {
等等,效果很好 但我知道随着元素的增加,for 循环的效率更高。
我试过了:
for (const guild of client.guilds.cache) {
console.log(guild.name)
但返回:未定义
如果我 console.log(guild) 我在控制台中获得了公会信息,名称绝对是其中的一部分
来自控制台:
[
'',
Guild {
members: GuildMemberManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]],
guild: [Circular]
},
channels: GuildChannelManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]],
guild: [Circular]
},
roles: RoleManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]],
guild: [Circular]
},
presences: PresenceManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]]
},
voiceStates: VoiceStateManager {
cacheType: [class Collection extends Collection],
cache: Collection [Map] {},
guild: [Circular]
},
deleted: false,
available: true,
id: '',
shardID: 0,
name: "GA's Testingserver!",
icon: '11a80a894a50cafd46c95451ed83f939',
splash: null,
discoverySplash: null,
region: 'europe',
memberCount: 5,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1598456514616,
defaultMessageNotifications: 'ALL',
systemChannelFlags: SystemChannelFlags { bitfield: 0 },
maximumMembers: 100000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '',
emojis: GuildEmojiManager {
cacheType: [class Collection extends Collection],
cache: [Collection [Map]],
guild: [Circular]
}
}
]
出于某种原因,我无法理解这个......
答案 0 :(得分:4)
根据 discord.js documentation,guild.cache
的类型为 collection
而不是 array
。
您可以遍历集合中的每个 guild
:
client.guilds.cache.each(guild => {
console.log(guild.name);
});
或者您可以遍历数组中的每个 guild
:
for (const guild of client.guilds.cache.array()) {
console.log(guild.name);
}