简体   繁体   English

有没有办法在 Node.js 中设置一个可能未定义为小写的变量?

[英]Is there a way to set a variable that could be undefined as lowercase in Node.js?

I'm making a discord.js bot that has commands that can have different parameters, such as mc!start vanilla, mc!start tekkit.我正在制作一个 discord.js bot,它的命令可以有不同的参数,例如 mc!start vanilla、mc!start tekkit。 Only singular string entries are allowed, as that's what I made it to do.只允许单个字符串条目,因为这就是我要做的。 But, if the user does not input a parameter, and just does mc!start, I want it to say that you cannot leave the parameter blank, but when I input only mc!start, the script gives me the "TypeError: Cannot read property 'toLowerCase' of undefined" error.但是,如果用户没有输入参数,而只是执行 mc!start,我想让它说你不能将参数留空,但是当我只输入 mc!start 时,脚本给了我“类型错误:无法读取未定义的属性“toLowerCase””错误。 I've been trying to do assignment functions and other things like that, but no cigar.我一直在尝试做分配功能和其他类似的事情,但没有雪茄。 Here is a splice of the code.这是代码的拼接。

client.on('message', (message) => {
    const messagearray = message.content.trim().split(' ');
    const command = messagearray[0];
    const minecraft_server = messagearray[1].toLowerCase();
    if(command === (`${prefix}help`)) {
        message.channel.send('Current Commands: !help, !start(Vanilla, Tekkit, Pixelmon, FarmingValley), !shutdown, !randomsong');
    }
    else if(command === (`${prefix}start`)) {
        if(mcVersions.indexOf(minecraft_server) === -1) {
// more code

Check whether the array element is set before trying to call methods of it.在尝试调用它的方法之前检查数组元素是否已设置。

const minecraft_server = messagearray[1] ? messagearray[1].toLowerCase() : "";

Instead of "" at the end you could provide a default server.您可以提供默认服务器,而不是末尾的""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM