首页 > 解决方案 > TypeError:无法读取未定义的属性“包含”:在 discord.js 中使用命令数组

问题描述

制作不和谐机器人可能会被标记为重复,但我找不到任何可以解决此类问题的东西。

使用此代码:

client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
    var args = message.content.slice(prefix.length).split(' ');
    const command = args.shift().toLowerCase();
    if(command === 'reactpoll' || command === 'rpoll' || command === 'reactionpoll') {
        if (!args.length) {
            return message.channel.send(`You didn't provide any arguments, ${message.author}! Use &rpoll (title) (Main Body)`);
        } else {

            if(!args[0].includes('(')) {
                message.channel.send('Incorrect Syntax: You need a \'(\'');
            } else {
                for(var e=0; e<args.length; e++) {
                    if(args[e].includes(')')) {
                        break;
                    }
                }
                //specifically here 
                if(!args[e].includes(')')) {
                    message.channel.send('Incorrect Syntax: You need a \')\'')
                    .catch();
                } else { 
                e++;
                if(!args[e].includes('{')) {
                    message.channel.send('Incorrect Syntax: You need a \'{\'');
                } else {
                    for(var e; e<args.length; e++) {
                        if(args[e].includes('}')) {
                            break;
                        }
                    }
                    e = args.length - 1;
                    if(!args[e].includes('}')) {
                        message.channel.send('Incorrect Syntax: You need a \'}\'');
                    } else {
                        var bigBoiString = args.join(' ');
                        var e1 = bigBoiString.replace("{", "");
                        var e2 = e1.replace("}", "");
                        var e3 = e2.replace("(", "**");
                        var e4 = e3.replace(")", "**:");
                        message.channel.send(e4);
                    }
                    }
                }
            }
        }
    }
});

我得到错误

C:\Users\MyName:)\Desktop\HappyDragonBot\bot.js:124
                if(!args[e].includes(')')) {
                            ^

我假设这意味着变量 e 没有分配给它的字符串,但是当我 console.log(e) 时,它给了我一个定义的值。此外,假设我运行命令&rpoll(嘿嘿嘿{嘿嘿嘿},我只需输入数字2而不是e,代码运行得很好。不知道我错过了什么。

标签: javascriptdiscord.js

解决方案


不是未定义的事实e并不意味着它args[e]不会是未定义的。问题是,如果这个循环:

                for(var e=0; e<args.length; e++) {
                    if(args[e].includes(')')) {
                        break;
                    }
                }

完成而不中断(因为没有参数包含 a )),然后e将等于args.length,因此args[e]将是未定义的。


推荐阅读