ASP经典如何更改另一个数组(不是真正的二维数组)持有的数组的长度

ASP Classic How to change the length of an array that is held by another array (not true 2d array)

我需要能够拥有一个二维数组,其中第二个数组的长度视具体情况而定。为此,我使用以下代码制作了一个包含其他数组的数组:

 Dim timeline
    ReDim timeline(days)

    for reDate = beginDate to endDate 
        timeline(DateDiff("d", beginDate, reDate)) = Array(0)
    next

我遇到的问题是我无法更改时间线包含的任何数组的大小,因为当我这样做时 ReDim 似乎不起作用。有谁知道我会怎么做?

试试下面的代码片段,使用 a 作为临时数组变量:

Dim timeline, a
ReDim timeline(days)

' initial fill the array
For reDate = beginDate to endDate
    a = Array()
    ReDim a(99)
    timeline(DateDiff("d", beginDate, reDate)) = a
Next

' redim sub arrays
For reDate = beginDate to endDate
    ' assign subarray to a
    a = timeline(DateDiff("d", beginDate, reDate))
    ' redim a
    ReDim Preserve a(199)
    ' put changed array into root array
    timeline(DateDiff("d", beginDate, reDate)) = a
Next

在这种情况下,每个子数组首先包含 100 个元素,在 redim 之后包含 200 个元素。

"Does not work" 和没有 code/context 的错误消息 ("Object required") 不是提出问题的最佳方式。第一个完全是浪费时间;第二个可能表明您在不应该使用的地方使用了 Set(VBScript 数组不是对象,因此代码中不应该有任何 Set)。

这证明了@omegastripes 指出的相同事实,但给出了可能存在的陷阱的提示:

Option Explicit

Dim AoA : AoA = Split("s o m e|w o r d s|o f|d i f f e r e n t|l e n g t h", "|")
Dim i
For i = 0 To UBound(AoA)
    AoA(i) = Split(AoA(i))
Next
WScript.Echo "----- test data:"
For i = 0 To UBound(AoA)
    WScript.Echo Join(AoA(i), "")
Next
WScript.Echo "----- array assignment copies (For Each elem ... does not 'work'):"
Dim e
For Each e In AoA
    e = "zap"
Next
For Each e In AoA
    WScript.Echo Join(e, "")
Next
WScript.Echo "----- array assignment copies (change needs index access):"
For i = 0 To UBound(AoA)
    e = AoA(i)
    e(0) = UCase(e(0)) ' just changes the copy (e)
    WScript.Echo Join(e, "")
    AoA(i)(1) = UCase(AoA(i)(1)) ' access via indices changes org collection
    WScript.Echo Join(AoA(i), "")
Next
WScript.Echo "----- replace whole subarrays (re-dimensioned dynamically):"
Dim n, m
For i = 0 To UBound(AoA)
    e = AoA(i)
    n = UBound(e)
    ReDim Preserve e(n * 2 + 1)
    For m = n + 1 To UBound(e)
        e(m) = UCase(e(m - n - 1))
    Next
    AoA(i) = e ' replace whole element
    WScript.Echo Join(AoA(i), "")
Next

输出:

cscript 37951664.vbs
----- test data:
some
words
of
different
length
----- array assignment copies (For Each elem ... does not 'work'):
some
words
of
different
length
----- array assignment copies:
Some
sOme
Words
wOrds
Of
oF
Different
dIfferent
Length
lEngth
----- replace whole subarrays:
sOmeSOME
wOrdsWORDS
oFOF
dIfferentDIFFERENT
lEngthLENGTH