如何正确编码/调试复杂的布尔条件

时间:2013-02-25 18:42:12

标签: javascript

是否可以按如下方式编写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
}

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

3 个答案:

答案 0 :(得分: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 
}

此外,您可以考虑按位操作,它可能更清晰。 Saludos,

答案 1 :(得分: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前三行测试不同的断言

答案 2 :(得分: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
}

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