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

时间:2011-10-05 01:18:57

标签: coffeescript

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

for cat in categories
  for job in jobs
    if condition
      do(this)
      ## Iterate to the next cat in the first loop

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

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

7 个答案:

答案 0 :(得分:35)

break就像js:

一样
for cat in categories
  for job in jobs
    if condition
      do this
      break ## Iterate to the next cat in the first loop

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

for cat in categories
    for job in jobs
      do this
      condition = job is 'something'
    do that unless condition

答案 1 :(得分:20)

使用labels。由于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

答案 2 :(得分:11)

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

答案 3 :(得分:3)

使用匿名循环返回

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

答案 4 :(得分:0)

Coffeescript永远不会有多个突发/继续声明,你必须坚持使用丑陋和过多的标志污染你的代码或尝试用do用lambda替换它并使用return作为多重中断

https://github.com/jashkenas/coffeescript/issues/4254

答案 5 :(得分:0)

要检查数组中的所有元素,可能lodash的every会有用吗?

this answer

for cat in categories
  if _.every jobs, conditionTerm
...

答案 6 :(得分:-22)

如果你想使用内部中断/继续,我想你的代码设计不是很好。 在我看来,任何编程语言都不允许这样做。

按照建议使用标签也被认为是不好的风格。