Applescript相当于"继续"?

dan*_*nez 34 applescript loops continue

我在AppleScript中有一个简单的'重复',并希望有条件地转到"重复"中的下一个项目.基本上我在寻找其他语言类似"继续"(或休息?)的东西.

我不熟悉AppleScript,但我现在发现它有用几次了.

Tom*_*rst 44

在搜索到这个确切的问题之后,我发现这本书在线提取.它完全回答了如何跳过当前迭代并直接跳转到repeat循环的下一次迭代的问题.

Applescript有exit repeat,它将完全结束一个循环,跳过所有剩余的迭代.这在无限循环中很有用,但在这种情况下不是我们想要的.

显然continue,AppleScript中不存在类似功能,但这是一个模拟它的技巧:

set aList to {"1", "2", "3", "4", "5"}

repeat with anItem in aList -- # actual loop
    repeat 1 times -- # fake loop
        set value to item 1 of anItem

        if value = "3" then exit repeat -- # simulated `continue`

        display dialog value
    end repeat
end repeat
Run Code Online (Sandbox Code Playgroud)

这将显示1,2,4和5的对话框.

在这里,你创建了两个循环:外部循环是你的实际循环,内部循环是一个只重复一次的循环.在exit repeat将退出内环与外环继续:正是我们想要的!

显然,如果你使用它,你将失去正常的能力exit repeat.

  • 在applescript 2.0 中,# 符号也允许用于评论:https://developer.apple.com/library/mac/documentation/applescript/conceptual/applescriptlangguide/conceptual/ASLR_lexical_conventions.html#//apple_ref/doc/uid/TP40000983- CH214-SW8 (2认同)
  • 无论如何,代码都会编译,因为“--”位于所有“#”之前,并且“--”始终在 AppleScript 中标记注释。 (2认同)

小智 7

set aList to {"1", "2", "3", "4", "5"}

repeat with anItem in aList -- # actual loop
    try
        set value to item 1 of anItem

        if value = "3" then error 0 -- # simulated `continue`

        log value
    end try
end repeat
Run Code Online (Sandbox Code Playgroud)

这仍然会给你"退出重复"的可能性


Dan*_*aug 6

set aList to {"1", "2", "3", "4", "5"}

repeat with anItem in aList -- # actual loop
    try -- # needed to simulate continue
        set value to item 1 of anItem
        if value = "3" then continueRepeat -- # simulated `continue` throws an error to exit the try block

        log value
    on error e
        if e does not contain "continueRepeat" then error e -- # Keeps error throwing intact
    end try
end repeat
Run Code Online (Sandbox Code Playgroud)

基于上面基于try块的方法,但读取稍微好一些.当然,由于未定义continueRepeat,因此将抛出错误,导致跳过try块的其余部分.

保持错误抛出完整包括引发任何意外错误的on error子句.