arrays - VBScript 中的零长度数组

标签 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

最佳答案

为了:

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)

将为 arr1 返回 -1,但为 arr2 和 arr3 返回“VBScript 运行时错误:下标超出范围:'UBound'”。

用于测试数组是“变暗”还是“空”的通用函数也应该(可能)测试变量是否实际上是一个数组。
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)

对我来说,99% 的时间当我检查数组是否“维度”时,是我是否需要获取数组的 UBound 并且我想在数组未维度的情况下防止运行时错误。所以我通常会将 UBound 作为参数传递,例如:
Function IsDimmedArray(arrParam, intUBoundParam)
    intUBoundParam = 0
    ...

我不知道这种做法是否真的节省了任何“时间”,但它几乎每次使用都节省了 1 行代码,并且是一种强制执行错误检查做法的简单方法。

此外,为了完整性,我将其包括在内,但在实践中,检查 “UBound >= 0”在 IsDimmedArray 中:
    If (llngError = 0) And (lintUBound >= 0) Then : IsDimmedArray = True

通常没有必要,因为通常它会在以下情况下使用:
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

因此,在这种情况下, lintUBound = -1 并且 For ... Next 将被跳过。

关于arrays - VBScript 中的零长度数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2108040/

相关文章:

javascript - angularjs ng-将嵌套数组重复到一个唯一列表中

vbscript - 如何启用 %UserProfile% 以使用文件夹重定向编写脚本?

dictionary - VBScript Dictionary Exists 方法总是返回 True

vbscript - VBS - 删除最后一个 "/"之后的部分字符串

regex - 如何正确搭配呢?

java - java中动态存储对象在未分配的对象中

java - 如何通过从文件中读取来反序列化 C++ 中的 ByteArray

c++ - 将 unsigned char* 数组转换为 std::string

php - 将数组对象转换为字符串并分隔值

javascript - iMacros 循环计数器的预定义值