我必须做一些ASP工作,我发现该语言没有提供检测零长度数组的方法(好吧,我想你可以检测到它们在你尝试使用它们时抛出的异常......).如果没有任何理智的方法来处理它,为什么Split()会返回一个空数组?或者我错过了什么?
我编造了以下hack以检测空数组,但必须有一种更简单的方法.这是什么?TIA
function ArrayEmpty (a)
dim i, res
res = true
for each i in a
res = false
exit for
next
ArrayEmpty = res
end function
Run Code Online (Sandbox Code Playgroud)
对于:
Dim arr1 : arr1 = Array()
Dim arr2
Dim arr3 : ReDim arr3(1) : Erase arr3
WScript.Echo UBound(arr1)
WScript.Echo UBound(arr2)
WScript.Echo UBound(arr3)
Run Code Online (Sandbox Code Playgroud)
对于arr1,将返回-1,但对于arr2和arr3,"VBScript运行时错误:下标超出范围:'UBound'".
测试数组是"Dimmed"还是"Empty"的通用函数也应该(可能)测试变量是否实际上是一个数组.
Function IsDimmedArray(arrParam)
Dim lintUBound : lintUBound = 0
Dim llngError : llngError = 0
IsDimmedArray = False
If Not IsArray(arrParam) Then : Exit Function
'' Test the bounds
On Error Resume Next
lintUBound = UBound(arrParam)
llngError = Err.Number
If (llngError <> 0) Then : Err.Clear
On Error Goto 0
If (llngError = 0) And (lintUBound >= 0) Then : IsDimmedArray = True
End Function ' IsDimmedArray(arrParam)
Run Code Online (Sandbox Code Playgroud)
对我来说,99%的时间我正在检查数组是否为"Dimensioned",如果我需要获取数组的UBound并且我想在数组未标注尺寸的情况下防止运行时错误.所以我通常会将UBound作为参数传递给:
Function IsDimmedArray(arrParam, intUBoundParam)
intUBoundParam = 0
...
Run Code Online (Sandbox Code Playgroud)
我不知道这种做法是否实际上保存了任何"时间",但它几乎每次使用都会保存1行代码,并且是一种简单的方法来强制执行错误检查.
另外,为了完整性,我将它包括在内,但实际上,在IsDimmedArray中检查"UBound> = 0":
If (llngError = 0) And (lintUBound >= 0) Then : IsDimmedArray = True
Run Code Online (Sandbox Code Playgroud)
通常不需要,因为通常它将用于以下情况:
Dim arrX
Dim lintUBound
Dim intNdx
arrX = Array()
lintUBound = UBound(arrX)
WScript.Echo "arrX is an array with UBound=" & lintUBound
For intNdx = 0 to lintUBound
WScript.Echo "This will not print: " & intNdx
Next
Run Code Online (Sandbox Code Playgroud)
因此,在这种情况下,lintUBound = -1并且将跳过For ... Next.
使用该Array函数创建或由其他内部VBScript函数(例如Split,)返回的空数组的上限为-1。因此,您可以测试一个空数组,如下所示:
Dim arr : arr = Array()
If UBound(arr) >= 0 Then
' arr is non-empty
Else
' arr is empty
End If
Run Code Online (Sandbox Code Playgroud)
此处的更多信息:测试空数组。
| 归档时间: |
|
| 查看次数: |
36021 次 |
| 最近记录: |