Javascript If语句内部的检查有问题

Javascript If语句内部的检查有问题,javascript,discord.js,Javascript,Discord.js,大家好,我对If语句有问题。我有两个检查里面,我不知道为什么其中一个不工作。很抱歉,如果我的代码不是最好的,而是初学者,我正在努力改进,非常感谢 如果command='hit'&&p3>0,则这是另一个命令 关于这个问题,您是正确的:}else if command=='hit'&&p3>0{中的代码永远不会运行 这是因为if/else语句在Javascript中的工作方式。解释器查看条件,如果条件为true,解释器将执行该块中的代码。如果条件为false,解释器将完全跳过该代码块并移动到下一个

大家好,我对If语句有问题。我有两个检查里面,我不知道为什么其中一个不工作。很抱歉,如果我的代码不是最好的,而是初学者,我正在努力改进,非常感谢

如果command='hit'&&p3>0,则这是另一个命令


关于这个问题,您是正确的:}else if command=='hit'&&p3>0{中的代码永远不会运行

这是因为if/else语句在Javascript中的工作方式。解释器查看条件,如果条件为true,解释器将执行该块中的代码。如果条件为false,解释器将完全跳过该代码块并移动到下一个条件

因此,在代码中,当command=='bj'时:

如果command==`bj`{//command是'bj',运行此代码块,跳过其他情况 var p1=0; var p2=0; 常量布尔=真; p1=Math.floorMath.random*11+1; p2=Math.floorMath.random*11+1; message.channel.send`第一张卡:`+p1; message.channel.send`第二张卡:`+p2; 变量p3=p1+p2; message.channel.send`total:`+p3; }否则,如果命令==`hit`&&p3>0{//此块不运行,则跳过它 message.channel.send`checking worked!`; }否则{//此块不运行,将跳过它 message.channel.send`不工作!`; } 现在,在您的代码中,当command==“hit”时:

如果command==`bj`{//command为'hit',则完全跳过此代码块 var p1=0; var p2=0; 常量布尔=真; p1=Math.floorMath.random*11+1; p2=Math.floorMath.random*11+1; message.channel.send`第一张卡:`+p1; message.channel.send`第二张卡:`+p2; 变量p3=p1+p2; message.channel.send`total:`+p3; }否则,如果command==`hit`&&p3>0{//command是'hit',但p3没有值-给定值的块永远不会运行! message.channel.send`checking worked!`; }否则{//此块不运行,将跳过它 message.channel.send`不工作!`; } 要获得所需的结果,需要重新考虑如何完成此操作。

因为您在单独的语句中声明了p2,所以在另一个if语句中它将不可读。如果要更新变量,请使用let,例如,让p2=Math.floorMath.random*11+1

如果您想从Javascript指南中获益,我建议您阅读本指南

此外,与其在主语句之外使用else if,为什么不使用2个if语句呢?它可以达到您想要的效果。下面是一个示例:

如果命令==`bj`{ 让commandState=1//state变量允许hit命令知道是否调用了bj命令,因为hit依赖于bj var p1=0; var p2=0; 常量布尔=真; p1=Math.floorMath.random*11+1; p2=Math.floorMath.random*11+1; message.channel.send`第一张卡:`+p1; message.channel.send`第二张卡:`+p2; 设p3=p1+p2; message.channel.send`total:`+p3; } 如果命令=='hit'{ if!commandState return;//如果命令状态不是1或true,请保留该语句 如果p3>0{ message.channel.sendSuccess }否则{ message.channel.sendFailure } } 您似乎还将反勾号用作字符串运算符。反勾号仅在需要在字符串中使用嵌入信息时使用,例如,`${message.author.id}`
使用普通引号在所有其他情况下都能很好地工作-选择您喜欢的示例1,“示例2”

p3仅在第一个块内定义。const Boolean=true的目的是什么?声明被提升,但赋值在代码执行时发生。因此在块内使用var声明p3使其成为全局的,但是,直到或除非执行var p3=p1+p2;行,它才有值。因此,如果command='bj'为false,则不会为其赋值。您的初始语句是正确的,但我不清楚解释。问题是,除非command=='bj',否则p3不会被赋值。如果改为执行else块,则不会被赋值签署一个值,而p3>0将始终为false,因为虽然p3已声明,但尚未为其赋值,因此其值未定义。是的,您在此处的评论非常清晰简洁

if (command == `bj`){

        var p1 = 0;
        var p2 = 0;
        
        const Boolean = true;

        p1 = Math.floor((Math.random() * 11) + 1);
        p2 = Math.floor((Math.random() * 11) + 1);
        message.channel.send(`First card: ` + p1);
        message.channel.send(`Second card: ` + p2);
        var p3 = p1 + p2;
        message.channel.send(`total : ` + p3);

    } else if (command == `hit` && p3 > 0){

        message.channel.send(`checking worked !`);

    } else {
            message.channel.send(`Not Working!`);
    }