2

我正在寻找优化循环而不使用布尔条件来检查如果循环正常终止而没有中断是否执行某些操作。在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 成语?

4

1 回答 1

3

对于这种特定用法,您可以使用 EcmaScript 6.find函数。如果你想兼容不支持 EcmaScript 6 的浏览器,Underscore.js 中也有类似的方法。

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

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

于 2013-12-31T16:54:51.833 回答