Coffeescript成语相当于Python的for / else?

时间:2013-12-31 16:47:59

标签: python for-loop coffeescript idioms for-else

我正在寻找优化循环而不使用布尔条件来检查如果循环正常终止而不中断则是否执行某些操作。在python中我写这个:

for x in lst:
    if cond(x):
       do_stuff_with(x)
       break
else:
    do_other_stuff()

在Coffeescript中,我能想到的最好的事情是做这样的事情:

found = false
for x in lst
    if cond x
        found = true
        do_stuff_with x
        break
if not found
    do_other_stuff()

这种情况是否有Coffeescript成语?

1 个答案:

答案 0 :(得分:3)

对于此特定用法,您可以使用EcmaScript 6 .find功能。如果您想与不支持EcmaScript 6的浏览器兼容,则Underscore.js中存在类似的方法。

result = lst.find cond
if result?
  do_stuff_with result
else
  do_other_stuff()

但是,没有直接替换Python的for else循环。在一般情况下,您需要声明一个布尔值来存储状态。