首页 > 解决方案 > 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!');
    }
} 

我有上面列出的其他人姓名的这些文件。有没有办法我可以做到这一点?

标签: javascript

解决方案


我会做这样的事情......

创建一个数组来存储有效名称的列表:

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

推荐阅读