Were `do…while` loops left out of CoffeeScript…?

前端 未结 5 509
栀梦
栀梦 2021-02-03 17:13

In CoffeeScript, the while loop comes standard:

while x()
   y()

However, the following1 doesn\'t work:



        
相关标签:
5条回答
  • 2021-02-03 17:45

    Your guess is correct: There is no do-while equivalent in CoffeeScript. So you'd typically write

    y()
    y() while x()
    

    If you find yourself doing this often, you might define a helper function:

    doWhile = (func, condition) ->
      func()
      func() while condition()
    
    0 讨论(0)
  • 2021-02-03 17:54

    I found this could be accomplished through a short circuit conditional:

    flag = y() while not flag? or x()
    
    0 讨论(0)
  • 2021-02-03 17:57

    I've been working on a project where I simply force the condition to evaluate at the end of the loop, then terminate at the beginning.

    # set the 'do' variable to pass the first time
    do = true
    while do
    
      # run your intended code
      x()
    
      # evaluate condition at the end of
      # the while code block
      do = condition
    
    # continue code
    

    It's not very elegant, but it does keep you from defining a new function just for your while code block and running it twice. There generally is a way to code around the do...while statements, but for those time that you can't you have a simple solution.

    0 讨论(0)
  • 2021-02-03 17:59

    I know that this answer is very old, but since I entered here via Google, I thought someone else might as well.

    To construct a do...while loop equivalent in CoffeeScript I think that this syntax emulates it the best and easiest and is very readable:

    while true
       # actions here
       break unless # conditions here
    
    0 讨论(0)
  • 2021-02-03 18:01

    The CoffeeScript documentation says:

    The only low-level loop that CoffeeScript provides is the while loop.

    I don't know of a built-in loop that executes at least once, so I guess the alternative is

    loop
      y()
      break if x()
    
    0 讨论(0)
提交回复
热议问题