简体   繁体   中英

Coffeescript idiom equivalent to Python's for/else?

I'm looking to optimize a loop without using a boolean conditional to check whether to perform some action if the loop terminates normally without breaking. In python I'd write this:

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

In Coffeescript the best I can think of is to do something like this:

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

Is there a Coffeescript idiom for this situation?

For this certain usage, you can use EcmaScript 6 .find function. Similar method exists in Underscore.js, if you want to be compatible with browsers not supporting EcmaScript 6.

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

However, there is no direct replacement for for else loop from Python. In general case, you will need to declare a boolean to store the state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM