【问题标题】:Discord.js - Help command returns "undefined" when a command doesn't have aliasesDiscord.js - 当命令没有别名时,帮助命令返回“未定义”
【发布时间】:2021-01-16 02:48:44
【问题描述】:

我的帮助命令返回有关命令的信息,当命令没有别名或使用属性时返回undefined

我的帮助命令代码:

const helpcommand = new Discord.MessageEmbed()
     .addField("Command name",
     `${command.name}`)
     .addField("Description",
     `${command.description}`)
     .addField("Aliases",
     `${command.aliases}`)
     .addField("Usage",
     `${command.usage}`)
     .setTimestamp()
     .setFooter(message.member.user.tag, message.author.avatarURL()); 
     message.channel.send(helpcommand)

我尝试添加 || 以使其在没有别名或用法时返回 none 但它不起作用:

const helpcommand = new Discord.MessageEmbed()
     .addField("Command name",
     `${command.name}`)
     .addField("Description",
     `${command.description}`)
     .addField("Aliases",
     `${command.aliases}` || "none")
     .addField("Usage",
     `${command.usage}` || "none")
     .setTimestamp()
     .setFooter(message.member.user.tag, message.author.avatarURL()); 
     message.channel.send(helpcommand)

谁能告诉我在没有可用属性时如何显示none

【问题讨论】:

    标签: javascript node.js discord.js


    【解决方案1】:

    Template literals 是允许嵌入表达式的字符串文字。如果command.aliasesundefined`${command.aliases}` 会将其转换为字符串"undefined"。由于非空字符串是 JavaScript 中的 truthy value,它会将其传递给 .addField() 而不是 none

    如果您像这样检查花括号内的值:${command.aliases || "none"} 在将其转换为字符串之前检查command.aliases 的值,因为它是undefined,即falsy value,它会回退到"none"

    所以你可以在花括号内检查它,或者你甚至可以去掉那些模板文字,因为它们不是必需的:

    const helpcommand = new Discord.MessageEmbed()
         .addField("Command name", command.name)
         .addField("Description", command.description)
         .addField("Aliases", command.aliases || "none")
         .addField("Usage", command.usage || "none")
         .setTimestamp()
         .setFooter(message.member.user.tag, message.author.avatarURL()); 
    
    message.channel.send(helpcommand);
    

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 2021-12-20
      • 2021-01-12
      • 2021-06-01
      • 1970-01-01
      • 2018-07-28
      • 2021-05-14
      • 2020-11-14
      • 1970-01-01
      相关资源
      最近更新 更多