javascript - 我在尝试使用 forEach 时遇到问题
问题描述
我正在尝试,当有人在公会 A/B/C(例如 3 个服务器中的机器人)中写入消息时,在第 4 个服务器中向我发送消息,并在名为“公会 A”的不同文本通道中发送它们,“公会B”和“公会C”,不在同一个...
我收到以下错误:
channel.send(msgLog)
TypeError: Cannot read property 'send' of undefined
这是我的代码:
const msgLog = `[#${message.channel.name}]=[${message.author.username}#${message.author.discriminator}]=> ${message.content}` ```
client.guilds.cache.map(guild => server.channels.cache.find(channel => channel.name == guild.name)).forEach(channel =>
channel.send(msgLog)
);
解决方案
错误意味着channel
是undefined
,并且您不能拥有 的任何属性(例如'send'
)undefined
。
这意味着server
没有guild.name
一些公会名称的频道。
您可以使用filter
仅包含定义的通道:
client.guilds.cache
.map(guild => server.channels.cache.find(channel => channel.name == guild.name))
.filter(channel => channel) // returns false if channel === undefined
.forEach(channel => channel.send(msgLog));
这大致相当于
client.guilds.cache.forEach(guild => {
const channel = server.channels.cache.find(channel => channel.name == guild.name));
if (channel) {
channel.send(msgLog);
}
});
推荐阅读
- kotlin - Kotlin 中相同的属性名称和主构造函数参数名称
- amazon-web-services - CloudFormation - 在禁用状态下创建 SNS 订阅
- c# - 为什么使用 ToListAsync 没有结果?
- python - 使用 SSHTunnelForwarder 功能 - 基于方式来保持连接?
- asp.net-mvc - 在中继器内部使用
- eclipse - 在 Eclipse 中引用外部文件:虚拟链接文件与项目属性中的构建设置?
- angular - 手动传递的 Angular 路由变量在组件中未定义
- android - Android 支持库文件夹没有更新版本
- python - NLP 分类器 - Python 太多的值无法解包
- reactjs - 在 React JS 中以编程方式重定向子组件内部不起作用