【问题标题】:How to use a switch structure where one case checks for arguments and another checks for no argument如何使用 switch 结构,其中一种情况检查参数,另一种情况检查无参数
【发布时间】:2018-06-16 11:47:19
【问题描述】:

我在使用 JavaScript 为 Discord 机器人创建“命令帮助页面”时遇到问题。

目前我的代码允许用户使用!help 调用命令,我需要创建一个使用参数的结构:

1) 通过比较if/else 语句中的参数并将消息发送到该组命令的通道来调用特定页面的帮助命令。 (例如:调用!help utility 会调出实用命令列表,!help general 会调出通用命令列表。

2) 如果不存在参数,则显示默认的命令页面。 (只需输入!help。)

我的想法是我应该使用if/else 语句来检查参数是否存在,但是我不知道这是否是正确的方法,或者如何做到这一点。

这是我正在尝试实现的一些代码。它不起作用,但它有我正在尝试实施的想法。

switch(argument[0]) {
    case "help":

        if(! argument[1]){
            var embed = new Discord.RichEmbed()
                .setTitle("General Commands")
                .setColor([60, 215, 115])
                .setDescription("Commands used throughout the server")
                .setTimestamp()
                break;
        } else if(argument[1] == 'utility') {
            var embed = new Discord.RichEmbed()
                .setTitle("Utility Commands")
                .setColor([60, 215, 115])
                .setDescription("Commands used by moderators")
                .setTimestamp()
                break;
        }
}

感谢您提前查看此内容。感谢您提供的任何帮助。

【问题讨论】:

  • 不起作用是什么意思?
  • 我的意思是if(! argument[1]){ 行没有正确测试是否正在输入参数。我发布了我想要的解决方案。

标签: javascript discord discord.js


【解决方案1】:

在这种情况下,我建议你在 switch 中使用 switch:

switch(argument[0]) {
    case "help":
        switch(argument[1])
        {
            case undefined:
            case "general":
                var embed = new Discord.RichEmbed()
                    .setTitle("General Commands")
                    .setColor([60, 215, 115])
                    .setDescription("Commands used throughout the server")
                    .setTimestamp()
                break;
            case "utility":
                var embed = new Discord.RichEmbed()
                    .setTitle("Utility Commands")
                    .setColor([60, 215, 115])
                    .setDescription("Commands used by moderators")
                    .setTimestamp()
                break;
        }
    break;
}

别忘了!help general 也应该可以工作。

【讨论】:

    【解决方案2】:

    我最终找到了答案。我必须对此进行测试:

     if(args[1] == undefined){
                var embed = new Discord.RichEmbed()
    

    args[1] == undefined 表示该参数没有用户输入,而只是采用!help 并显示常规帮助屏幕。

    证明只需要一点研究,你就可以弄清楚任何事情! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 2013-05-13
      • 2022-08-04
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多