VBScript中的“继续”(到下一个迭代)
我和一位同事试图找出一种方法,该方法等效于VBScript“ For / Next”循环中的“ continue”语句。
我们看到的每个地方都发现,如果没有讨厌的嵌套,人们就无法在VBScript中执行此操作,这对我们来说不是一个选择,因为这是一个很大的循环。
我们想到了这个主意。 它会像“继续(继续下一个迭代)”那样工作吗? 有没有人有更好的解决方法或改进建议?
For i=1 to N
For workaroundloop = 1 to 1
[Code]
If Condition1 Then
Exit For
End If
[MoreCode]
If Condition2 Then
Exit For
End If
[MoreCode]
If Condition2 Then
Exit For
End If
[...]
Next
Next
感谢您的意见
您的建议会起作用,但是使用Do循环可能会更具可读性。
实际上,这是C语言中的一个惯用法-如果您想尽早退出构造,可以使用break语句使用do {} while(0)循环,而不使用goto。
Dim i
For i = 0 To 10
Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False
Next
就像暗恋所暗示的那样,如果删除额外的缩进级别,它看起来会更好一些。
Dim i
For i = 0 To 10: Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False: Next
我决定采用的解决方案涉及使用布尔变量来跟踪:
循环是否应处理其指令或跳至下一个迭代:
Dim continue
For Each item In collection
continue = True
If condition1 Then continue = False End If
If continue Then
'Do work
End If
Next
我发现嵌套循环解决方案在可读性方面有些混乱。 此方法也有其自身的陷阱,因为遇到:
之后,循环不会立即跳到下一个迭代。以后的条件可能会反转continue
的状态。它在初始循环中还有一个辅助构造,并且 需要声明一个额外的var。
哦,VBScript。。。
另外,如果您要使用可接受的答案,这在可读性方面还算不错,那么您可以将其与:
结合使用,将两个循环合并为一个循环:
Dim i
For i = 0 To 10 : Do
If i = 4 Then Exit Do
WScript.Echo i
Loop While False : Next
我发现消除多余的缩进级别很有用。
一种选择是将所有代码放入Goto
内的循环中,然后在要“继续”时从该Goto
返回。
虽然并不完美,但是我认为额外的循环会减少混乱。
编辑:或者我想,如果您足够勇敢,您可以使用Goto
以某种方式跳转到循环的开头(确保计数器正确更新),我认为VBScript支持该功能,但是如果 有人发现您在代码中使用Goto
:)
我过去经常使用Do,Loop,但是我已经开始使用Sub或Function了,而我可能会退出。 在我看来,这似乎更干净。 如果您需要的变量不是全局变量,则还需要将它们传递给Sub。
For i=1 to N
DoWork i
Next
Sub DoWork(i)
[Code]
If Condition1 Then
Exit Sub
End If
[MoreCode]
If Condition2 Then
Exit Sub
End If
[MoreCode]
If Condition2 Then
Exit Sub
End If
[...]
End Sub
将迭代实现为递归函数。
Function Iterate( i , N )
If i == N Then
Exit Function
End If
[Code]
If Condition1 Then
Call Iterate( i+1, N );
Exit Function
End If
[Code]
If Condition2 Then
Call Iterate( i+1, N );
Exit Function
End If
Call Iterate( i+1, N );
End Function
从调用Iterate(1,N)开始
我们可以使用单独的函数来执行continue语句。 假设您有以下问题:
for i=1 to 10
if(condition) then 'for loop body'
contionue
End If
Next
在这里,我们将对for循环主体使用函数调用:
for i=1 to 10
Call loopbody()
next
function loopbody()
if(condition) then 'for loop body'
Exit Function
End If
End Function
循环将继续执行功能退出语句。
尝试使用While / Wend和Do While / Loop语句...
i = 1
While i < N + 1
Do While true
[Code]
If Condition1 Then
Exit Do
End If
[MoreCode]
If Condition2 Then
Exit Do
End If
[...]
Exit Do
Loop
Wend
我认为您打算在您的break
语句下包含“所有逻辑”。 基本上:
' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
' you want to say
' If i = 4 CONTINUE but VBScript has no continue
If i <> 4 Then ' just invert the logic
WSH.Echo( i )
End If
Next
这可以使代码更长一些,但是无论如何,有些人不喜欢break
或continue
。