1

是否可以编写如下 if 语句:

if(a === 0 && (b === 0 || c === 0)){
    if(b === 0 && c === 0){
        //a, b, and c are equal to 0
    }
    else if(b === 0){
        //only a and b are equal to 0
    }
    else {
        //only a and c are equal to 0
    }
}
else {
    //a doesn't equal 0, but b or c could so we test those
}

它似乎在我以类似方式编写的代码中不起作用......也许我写错了?这在我的脑海中是有道理的。如何构建我的代码以避免这样的混淆?

4

3 回答 3

2

我纠正了你的其他:

if(a === 0 && (b === 0 || c === 0)){
    if(b === 0 && c === 0){
        //a, b, and c are equal to 0
    }
    else if(b === 0){
        //only a and b are equal to 0
    }
    else {
        //only a and c are equal to 0
    }
}
else {
    //   a === 0 and neither b nor c === 0,
    //or a!==0 and neither b nor c === 0,
    //or a!==0 and either b or c or both === 0 
}

我的提议:

if(a === 0 && (b === 0 || c === 0)){
    if(b === 0 && c === 0){
        //a, b, and c are equal to 0
    }
    else if(b === 0){
        //only a and b are equal to 0
    }
    else {
        //only a and c are equal to 0
    }
} else if (a === 0) {
    //a === 0 and neither b nor c === 0,
} else {
    //   a!==0 and neither b nor c === 0,
    //or a!==0 and either b or c or both === 0 
}

另外,您可以考虑按位运算,它可能会更清楚。萨卢多斯,

于 2013-02-25T18:48:06.813 回答
2

我只是会以不同的编码方式编写它,但是您发布的内容按预期工作

http://jsfiddle.net/u2ert/

a=0;
b=0;
c=0;

if(a === 0 && (b === 0 || c === 0)){
    if(b === 0 && c === 0){
        alert("//a, b, and c are equal to 0");
    }
    else if(b === 0){
        alert("//only a and b are equal to 0");
    }
    else {
        alert("//only a and c are equal to 0");
    }
}

changhe 前三行来测试不同的断言

于 2013-02-25T18:51:09.297 回答
0

为什么要在注释中写你可以在代码中写的东西......?

if(a === 0 && (b === 0 || c === 0)){
    if(a === 0 && b === 0 && c === 0){

    }
    else if(a === 0 && b === 0){

    }
    else if (a === 0 && c === 0 ) {

    }
    else {
        console.log("Boolean logic wrong: " + (a===0) + ", " + (b===0) + ", " + (c===0)
        // throw error
    }
}
else {
// print out the values of a, b, c here if you are confused
}

此外,这是自调试的,因此您不会对布尔逻辑感到困惑。

于 2013-02-25T18:45:44.460 回答