javascript - Javascript - 我可以将特定命令合并到一个文件中,而将其他命令合并到另一个文件中吗?
问题描述
我目前正在通过 Javascript 制作 Discord 机器人,但我想巧妙地清理我的代码,因为我的 main.js 文件中有太多“else if”语句。例如,if 语句的开头应该调用另一个名为“ping”的文件的代码。但与以 if 循环的形式对每个人的姓名执行此操作相反,我只想将所有这些都放在一个专用于姓名的文件中。
目前,这是我在 main.js 上的代码的样子:
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
} else if (command == 'gaurav'){
client.commands.get('gaurav').execute(message, args);
} else if (command == 'will') {
client.commands.get('will').execute(message, args);
} else if (command == 'michael') {
client.commands.get('michael').execute(message, args);
} else if (command == 'jorin') {
client.commands.get('jorin').execute(message, args);
} else if (command == 'reid') {
client.commands.get('reid').execute(message, args);
} else if (command == 'emily') {
client.commands.get('emily').execute(message, args);
} else if (command == 'eildert') {
client.commands.get('eildert').execute(message, args);
} else if (command == 'julian') {
client.commands.get('julian ').execute(message, args);
}
在“ping”文件中,我有
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args) {
message.channel.send('pong!');
}
}
我有上面列出的其他人姓名的这些文件。有没有办法我可以做到这一点?
解决方案
我会做这样的事情......
创建一个数组来存储有效名称的列表:
let names = [
'ping',
'gaurav',
'will',
'michael',
'jorin',
'reid',
'emily',
'eildert',
'julian'
];
然后您只需检查该数组中是否有您想要的名称。通过创建一个包含您要检查的名称的变量来做到这一点:
let checkForThisName
您必须指定checkForThisName
要检查的名称。有不同的方法可以做到这一点。
然后检查数组checkForThisName
if (names.includes(checkForThisName)) {
client.commands.get(checkForThisName).execute(message, args);
};
推荐阅读
- kubernetes - 气流服务尚未启动
- c# - 如何调用对象类函数
- python - 在 findall() 中提供字符串时,Python BeautifulSoup 会改变行为
- webserver - 如何在 AS/400 上添加 Web 界面?
- oracle - 生成没有外键约束的 oracle ERD
- javascript - react-owlcarousel的样式..我如何用我的覆盖生成的类
- python - 在没有安装 Python 的情况下构建 Python 可执行文件以在 PC 上运行
- c - 使用scanf或fgets更好吗?
- wavesplatform - 如何在 Waves 中解码附件?
- postgresql - TypeOrm 不会在更新时保存实体及其关系