Multiple conditions in for loop

前端 未结 2 1314
失恋的感觉
失恋的感觉 2020-12-19 01:52

How can I write a for loop with multiple conditions?

Intended Javascript:

for(k=1; k < 120 && myThing.someValue > 1234; k++){
  myThing         


        
相关标签:
2条回答
  • 2020-12-19 02:51

    Since a for loop is equivalent to a while loop plus a couple of statements, and CoffeeScript offers only one kind of for loop, use a while loop. If you’re trying to get specific JavaScript output, you should probably not be using CoffeeScript.

    Of course, there is always

    `for(k=1; k < 120 && myThing.someValue > 1234; k++) {`
    do myThing.action
    `}`
    

    Avoid.

    0 讨论(0)
  • 2020-12-19 02:51

    Trying to write CoffeeScript that produces specific JavaScript is a bit silly and pointless so don't do that.

    Instead, translate the code's intent to CoffeeScript. You could say:

    for k in [1...120]
        break if(myThing.someValue <= 1234)
        myThing.action()
    

    And if you're not actually using the loop index for anything, leave it out:

    for [1...120]
        break if(myThing.someValue <= 1234)
        myThing.action()
    

    Both of those produce JavaScript that is structured like this:

    for(k = 1; k < 120; k++) {
        if(myThing.someValue <= 1234)
            break;
        myThing.action();
    }
    

    That should have the same effect as your loop. Furthermore, I tend to think that those three loops are more maintainable than your original as they don't hide the exceptional condition inside the loop condition, they put it right in your face so you can't miss it; this is, of course, just my opinion.

    0 讨论(0)
提交回复
热议问题