如果属性未定义,请跳到其他地方

时间:2019-02-12 15:44:55

标签: javascript mysql node.js discord.js

我具有创建团队并将数据放入数据库的功能。现在,我正在尝试检查团队是否已经存在,如果确实存在,请回复消息。我的if语句有问题。

  

如果(结果为[0] .teamname == teamName)

当未定义result [0] .teamname时,它显示无法读取未定义的属性“ teamname”,它将忽略else并引发错误。我该如何做才能使自己不被忽视?

这是我用来创建团队的功能。

function createTeam(teamName, members, message) {
teamName = teamName.replace("_", " ");
let insertTeam = `INSERT INTO teams (teamname) VALUES ('${teamName}');`;

db.select(`SELECT id_t, teamname FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
    if (err) {
        throw err;
    } else {
        if (result[0].teamname == teamName) {
            if (message.guild !== null) message.delete();

            message.reply("this team already exists!");
        } else {
            db.query(insertTeam);

            db.select(`SELECT id_t FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
                if (err) {
                    throw err;
                } else {
                    for (let i = 0; i < members.length; i++) db.query(`INSERT INTO team_user (user, team) VALUES ('${members[i]}' , ${result[0].id_t})`);
                }
            });

            if (message.guild !== null) message.delete();

            let newTeam = new Discord.RichEmbed()
            .setThumbnail("https://cdn.discordapp.com/emojis/542789472421675028.png?v=1")
            .setColor("#15f153")
            .addField("New team has been created!", `Team ${teamName} has been created with total of ${members.length} members!\nGood luck!`);

            message.channel.send(newTeam);
        }
    }
});

到目前为止我尝试过什么:

  1. 检查result [0] .teamname是否未定义
  2. 检查结果长度是否不为0
  3. try-catch语句

4 个答案:

答案 0 :(得分:2)

if(结果[0] &&结果[0] .teamname == teamName)

首先,您需要检查result [0]是否未定义

答案 1 :(得分:1)

您需要short-circuit条件。这意味着您要先检查result是否存在,然后再检查result的属性

因此,例如,您的代码应如下所示:

if (result && result[0] && result[0].teamname == teamName) {
    //Do something
}

答案 2 :(得分:0)

如果结果是具有多于一个值的数组,那么您需要遍历每个值,可以为此使用过滤器数组方法:

var found = result.filter((row) => row.teamname == teamName);

if (found.length) {

}

如果结果未定义,您也可以在评论检查中提及@ThomasKleßen:

var found = result && result.filter((row) => row.teamname == teamName).length;

if (found) {

}

答案 3 :(得分:0)

您始终可以设置默认值

if ((result || [{}])[0].teamname == teamName)

如果结果是虚假的,它将默认为一个空对象的数组,这将允许该数组访问和点表示法起作用,但相等性将失败。