在Coffeescript中打破/继续嵌套for循环

Eng*_*gan 26 coffeescript

如何在Coffeescript中打破/继续嵌套循环?我有类似的东西:

for cat in categories
  for job in jobs
    if condition
      do(this)
      ## Iterate to the next cat in the first loop
Run Code Online (Sandbox Code Playgroud)

另外,有没有办法将整个第二个循环作为条件包装到第一个循环中的另一个函数?例如

for cat in categories
  if conditionTerm == job for job in jobs
    do(this)
    ## Iterate to the next cat in the first loop
  do(that) ## Execute upon eliminating all possibilities in the second for loop,
           ## but don't if the 'if conditionTerm' was met
Run Code Online (Sandbox Code Playgroud)

Ric*_*asi 36

break 就像js一样工作:

for cat in categories
  for job in jobs
    if condition
      do this
      break ## Iterate to the next cat in the first loop
Run Code Online (Sandbox Code Playgroud)

你的第二个案例不是很清楚,但我认为你想要这个:

for cat in categories
    for job in jobs
      do this
      condition = job is 'something'
    do that unless condition
Run Code Online (Sandbox Code Playgroud)


mat*_*tyr 19

使用标签.由于CoffeeScript不支持它们,所以你需要这样做:

0 && dummy
`CAT: //`
for cat in categories
  for job in jobs
    if conditionTerm == job
      do this
      `continue CAT` ## Iterate to the next cat in the first loop
  do that ## Execute upon eliminating all possibilities in the second for loop,
          ## but don't if the 'if conditionTerm' was met
Run Code Online (Sandbox Code Playgroud)

  • 这是GOTO:? (4认同)

tol*_*ark 10

Coffescript的"break"只打破了直接循环,无法识别外部循环的破坏(烦人!).以下hack在某些情况下适用于在满足条件时中断多个循环:

ar1 = [1,2,3,4]
ar2 = [5,6,7,8]

for num1 in ar1
  for num2 in ar2
    console.log num1 + ' : ' + num2
    if num2 == 6
      breakLoop1 = true; break 
  break if breakLoop1

# Will print:
# 1 : 5
# 1 : 6
Run Code Online (Sandbox Code Playgroud)


uri*_*ald 5

使用带返回的匿名循环

do ->
  for a in A
    for b in B 
      for c in C
        for d in D
          for e in E
            for f in F
              for g in G
                for h in H
                  for i in I
                    #DO SOMETHING
                    if (condition)
                      return true
Run Code Online (Sandbox Code Playgroud)