javascript中的多个if语句

时间:2016-03-12 12:36:30

标签: javascript if-statement

我有原因:

if(
                (attackX > enemies[enemy].posX && attackX < enemies[enemy].posX + enemies[enemy].width) || (attackX + 32 > enemies[enemy].posX && attackX + 32 < enemies[enemy].posX + enemies[enemy].width)
                &&
                (attackY > enemies[enemy].posY && attackY < enemies[enemy].posY + enemies[enemy].height) || (attackY + 32 > enemies[enemy].posY && attackY + 32 < enemies[enemy].posY + enemies[enemy].height)
            ){ //CODE }

console.log(attackX > enemies[enemy].posX && attackX < enemies[enemy].posX + enemies[enemy].width); //true
        console.log(attackX + 32 > enemies[enemy].posX && attackX + 32 < enemies[enemy].posX + enemies[enemy].width); //false
        console.log(attackY > enemies[enemy].posY && attackY < enemies[enemy].posY + enemies[enemy].height); //false
        console.log(attackY + 32 > enemies[enemy].posY && attackY + 32 < enemies[enemy].posY + enemies[enemy].height); //false

在那种情况下工作,但我不知道为什么(有AND操作员)

1 个答案:

答案 0 :(得分:1)

查看operator precendence

&amp;&amp;具有更高的优先权,从而首先评估 - &gt;你得到 true || (false && false) || false会产生true。要解决此问题,请将||语句组放在括号中。