开发者

How can I determine if a dynamic array has not be dimensioned in VBScript

Say I create a dynamic array in VBScript

Dim myArray()

Later on how can I check to see that this array has never been 开发者_运维问答dimensioned?

Ubound(myArray) 'sub script out of range
Lbound(myArray) 'sub script out of range
IsEmpty(myArray) 'returns false


I don't think there's anything built in, but you can create your own function as:

Function IsInitialized(a)    
    Err.Clear
    On Error Resume Next
    UBound(a)
    If (Err.Number = 0) Then 
        IsInitialized = True
    End If
End Function

Which you can then call as:

Dim myArray()
If Not IsInitialized(myarray) Then
    WScript.Echo "Uninitialized"
End If

However, one way to work around it might be to not declare empty arrays, instead declare just a variable and set it to an array later, so change the code above to:

Dim myArray
myArray = Array()
If Not IsInitialized(myarray) Then
    WScript.Echo "Uninitialized"
End If


I prefer to Not the Array, and then compare the result to -1. This works, and does so without intentionally causing an error.

Dim myArray()

...

If (Not myArray) = -1 Then
    ReDim myArray(0)
Else
    ReDim Preserve(0 To UBound(myArray)+1)
End If


I've been using something like this:

Dim arr
arr = null

sub addElement (byref arr, element)
    if isNull (arr) then
        redim arr(0)
    else
        redim preserve arr (uBound(arr) + 1)
    end if
    arr(uBound(arr)) = element
end sub


Came across this while looking for an answer to the same question, I initialized a variable to 0 and increment it only when I add to the area and then just check for the variable value instead...

dim myarray() num=-1 if addtoarray then num=num+1 redim preserve myarray(num) end if if num>-1 then do something end if

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜