我有一个简单的“repeat with”循环在AppleScript中,并且想要条件性地继续下一个项目。基本上,我正在寻找类似于其他语言中的“continue”(或break?)的东西。
我对AppleScript不是很熟悉,但现在已经发现了它的一些用途。
我对AppleScript不是很熟悉,但现在已经发现了它的一些用途。
repeat
循环的下一次迭代的问题。exit repeat
,它将完全结束循环,跳过所有剩余的迭代。这在无限循环中可能很有用,但在这种情况下不是我们想要的。continue
的功能,但这里有一个模拟它的技巧: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
这将显示1、2、4和5的对话框。
在这里,您创建了两个循环:外部循环是实际循环,内部循环是仅重复一次的循环。 exit repeat
将退出内部循环,并继续进行外部循环:正是我们想要的!
显然,如果您使用此方法,您将失去执行正常的 exit repeat
的能力。
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
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
-- 或者你可以采用不同的策略:使用循环来循环,并在处理程序中执行条件逻辑,如下所示:
set aList to {"1", "2", "3", "4", "5"}
repeat with anItem in aList
doConditionalWork(anItem as string)
end repeat
on doConditionalWork(value)
if value = "3" then return
display dialog value
end doConditionalWork
大家都把它搞得太复杂了。试试这个:
set aList to {"1", "2", "3", "4", "5"}
repeat with anItem in aList
set value to item 1 of anItem
if value is not "3" then log value
end repeat
基于Tom Lokhorst的答案,这里提供了一种根据你设置的isExit
变量来执行break
或continue
的变体方法。
因此,在外部(非虚假)循环的末尾,您需要添加以下代码:
if isExit then
exit repeat
end if
这样,如果isExit
为真,你只需要退出外部循环,成为一个有效的break
。
对于原始问题,问题看起来像这样,下面将是一个概括性的问题。
set aList to {"1", "2", "3", "4", "5"}
repeat with anItem in aList -- actual loop
set isExit to false
repeat 1 times -- fake loop
-- do your stuff
set value to item 1 of anItem
if value = "3" then
-- simulated `continue`
set isExit to false
exit repeat
end if
if value = "69" then
-- simulated `break`
set isExit to true
exit repeat
end if
display dialog value
end repeat
if isExit then
exit repeat
end if
end repeat
为了更容易理解,我们来看一个简单的例子:
假设你想在这两个if
语句中使用continue
或break
,你可以将所有代码放在它们之间,我只包含了与不同退出策略相关的代码。
如果你想写出类似下面的代码:
repeat <condition_repeat>
if <condition_continue> then
continue
end if
if <condition_break> then
break
end if
end repeat
这可以写成
repeat <condition_repeat>
set isExit to false -- added
repeat 1 times -- added
if <condition_continue> then
set isExit to false -- changed
exit repeat -- changed
end if
if <condition_break> then
set isExit to true -- changed
exit repeat -- changed
end if
end repeat -- added
if isExit then -- added
exit repeat -- added
end if -- added
end repeat
无法获取""的第一个项目。
- Max Well