VBScript create a multi-dimensional array and add to it?

后端 未结 3 1727
一整个雨季
一整个雨季 2021-01-13 15:55

This is a doozy for me haha, I\'ve pretty much checked nearly every page on Google Search and I still don\'t quiet understand how to do it.

I want to create a multi

3条回答
  •  难免孤独
    2021-01-13 16:31

    (1) The best way to get an ADO resultset into a two-dimensional array is to use the .GetRows method. Then your problem just vanishes.

    (2) There are two kind of arrays in VBScript. Fixed arrays are declared by specifying their UBounds:

    Dim aFix(2, 3)
    

    They can't be resized. Dynamic arrays can be changed by ReDim [Preserve]. The best way to create such an array is

    ReDim aDyn(2, 3)
    

    if you know the starting size, or

    Dim aDyn : aDyn = Array()
    

    if you want to start with an empty one. The catch 22 is: you can use Preserve only for the last dimension.

    (3) Your

    Dim data2()
    

    is an abomination - a fixed array of no size. It's a pity that the 'compiler' is too stupid to catch such a beast that VBScript can't handle properly:

    >> Dim data2()
    >> WScript.Echo UBound(data2)
    >>
    Error Number:       9
    Error Description:  Subscript out of range
    

    The nastiness of the Dim a() statement is hidden by the fact that a later ReDim will store a proper dynamic array into that variable:

    >> Dim data2() ' <-- abomination
    >> ReDim data2(1,1) ' <-- overwritten by a dynamic array
    >> data2(0,0) = 0
    >> ReDim Preserve data2(1,5) ' last dimension increased; 'old' data preserved
    >> data2(1,5) = 1
    >> WScript.Echo data2(0,0), data2(1,5)
    >>
    0 1
    

    Update wrt jmbpiano's comment:

    (1) I gave evidence that you can't get the UBound for a variable dimmed with (), so I stick to my claim that such beasts are abominations. Just look at the question (or this one) to see that using the () will give you trouble.

    (2) I said that you should use ReDim a(KnownUbound) to 'declare' a dynamic array with known size, but I didn't give evidence for the 'Option Explicit'-compatibility of this idiom. So :

    Option Explicit
    ReDim a(4711)
    ReDim b(4,7,1,1)
    a(0) = "qed"
    b(0,0,0,0) = "qed"
    WScript.Echo b(0,0,0,0)
    

    output:

    cscript 19888987.vbs
    qed
    

提交回复
热议问题