VBScript中的零长度数组

ang*_*gus 12 arrays vbscript

我必须做一些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)

Kev*_*gan 6

对于:

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.


Hel*_*len 5

使用该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)

此处的更多信息:测试空数组

  • 您的代码不正确,因为UBound在空数组上失败。您链接的页面证实了我的怀疑,唯一的办法是通过检测是否引发了异常(或由我的“ for each” hack)。真可悲:-/ (4认同)
  • @angus:他是正确的,因为他的代码看起来像“暗淡的结果:results = Array()” (2认同)
  • Helen的答案在第一行有关键点-“使用Array函数...”。答案中缺少的是对您做错了的解释。这就是@Totonga指出的内容:如果像这样“ Dim someArray()”声明数组,则它们UBound将返回未定义。如果您这样声明“ Dim someArray:Array()”,则UBound将返回-1。 (2认同)