开发者

What's the cleanest way to branch based on which conditional broke a while loop in Javascript?

Say I've got this loop

while(condition1 && condition2 && conditio开发者_JAVA百科n3 && condition4){
     browseReddit();
}

if (!condition1){}
if (!condition2){}
if (!condition3){}
if (!condition4){}

It could be broken by any of the 4 conditions becoming false, and I would want to execute different code based on which one(s) it was. Ideally, I would not like to evaluate them all more than I absolutely have to. Assume browseReddit() forces us to evaluate them all again.

Putting an if chain after the loop is how I'm doing it currently. Is there a cleaner way? value brevity above all else in your answer.


while (1) {
    stop = 0;
    if (!condition1) {
        // condition 1 code
        stop = 1;
    }
    if (!condition2) {
        // condition 2 code
        stop = 1;
    }
    if (!condition3) {
        // condition 3 code
        stop = 1;
    }
    if (!condition4) {
        // condition 4 code
        stop = 1;
    }
    if (stop) {
        break;
    }
    browseReddit();
}


Final edit:

while((condition1||function(){alert("condition1 failed!");}()) & 
      (condition2||function(){alert("condition2 failed!");}()) &
      (condition3||function(){alert("condition3 failed!");}()) &
      (condition4||function(){alert("condition4 failed!");}())){
   browseReddit();
}

jsfiddle: http://jsfiddle.net/ctrlfrk/HjftT/3/


I would go with the way you have in your current code sample, so that you don't exempt yourself from testing all four of your exit cases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜