为什么我的if else语句返回错误的结果?

时间:2014-04-16 10:13:37

标签: javascript if-statement

我的Main.js文件中有以下if else语句:

var fixA = "Trap";
var fixB = "Ball";

console.log(fixA); 
console.log(fixB);

if (fixA == "Mouse" || fixA == "Ball" && fixB == "Mouse" || fixB == "Ball") {
    console.log("Ball hit mouse");
}else if (
    fixA == "Trap" || fixA == "Ball" && fixB == "Trap" || fixB == "Ball") {
    console.log("Ball hit trap"); 
}else if (
    fixA == "Trap" || fixA == "Mouse" && fixB == "Trap" || fixB == "Mouse") {
    console.log("Trap hit mouse");
}

在我的原始陈述中,fixAfixB变量是根据彼此碰撞的对象分配的,这些变量不起作用。它一直显示" Ball hit mouse",if()的结果。

自己寻找问题我给了fixAfixB一个固定字符串,这又产生了相同的输出。在设置变量后,即使我的前两个控制台日志也会记录正确的字符串。所以声明本身一定有问题。我做了一些阅读,研究等等,但我似乎无法弄清楚它有什么不对。

有人能帮助我吗?

2 个答案:

答案 0 :(得分:4)

查看JavaScript的operator precendece&&运算符绑定比||运算符强。您可以通过在条件中添加parantheses来规避此行为。

if ( (fixA == "Mouse" || fixA == "Ball") && (fixB == "Mouse" || fixB == "Ball")) {
    console.log("Ball hit mouse");
}else if (
    (fixA == "Trap" || fixA == "Ball") && (fixB == "Trap" || fixB == "Ball")) {
    console.log("Ball hit trap"); 
}else if (
    (fixA == "Trap" || fixA == "Mouse") && (fixB == "Trap" || fixB == "Mouse")) {
    console.log("Trap hit mouse");
}

答案 1 :(得分:4)

这里有2个级别的错误。一个是运算符优先级:

// your code
fixA == "Mouse" || fixA == "Ball" && fixB == "Mouse" || fixB == "Ball" 
// how it works
(fixA == "Mouse") || ((fixA == "Ball" && fixB == "Mouse") || (fixB == "Ball" ))
// what I assume you wanted
(fixA == "Mouse" || fixA == "Ball") && (fixB == "Mouse" || fixB == "Ball")

但这仍然是不正确的,因为它也会触发鼠标 - 鼠标或球 - 球,而不仅仅是鼠标球。

您需要的条件如下:

(fixA == "Mouse" && fixB == "Ball") || (fixA == "Ball" && fixB == "Mouse")