无法ReDim保留数据的多维数组

时间:2018-01-26 12:06:04

标签: arrays multidimensional-array vbscript

有没有人知道为什么我可以ReDim没有Preserve关键字的多维数组,但是如果我想保留它会失败?这似乎在一维数组上工作正常。

这样可以删除旧数据:

Dim marray()
ReDim marray(2,3)
WScript.Echo "marray ubound = " & UBound(marray)

marray(0, 0) = "item 0,0"
marray(0, 1) = "item 0,1"
marray(0, 2) = "item 0,2"
marray(0, 3) = "item 0,3"
marray(1, 0) = "item 1,0"
marray(1, 1) = "item 1,1"
marray(1, 2) = "item 1,2"
marray(1, 3) = "item 1,3"
marray(2, 0) = "item 2,0"
marray(2, 1) = "item 2,1"
marray(2, 2) = "item 2,2"
marray(2, 3) = "item 2,3"

For Each item In marray
    WScript.Echo item
Next

ReDim marray(UBound(marray)+2, 3)
WScript.Echo "New marray ubound = " & UBound(marray)
marray(3, 0) = "item 3,0"
marray(3, 1) = "item 3,1"
marray(3, 2) = "item 3,2"
marray(3, 3) = "item 3,3"
marray(4, 0) = "item 4,0"
marray(4, 1) = "item 4,1"
marray(4, 2) = "item 4,2"
marray(4, 3) = "item 4,3"

For Each item In marray
    WScript.Echo item
Next

这应保留数据,但不起作用。

Dim marray()
ReDim marray(2,3)
WScript.Echo "marray ubound = " & UBound(marray)

marray(0, 0) = "item 0,0"
marray(0, 1) = "item 0,1"
marray(0, 2) = "item 0,2"
marray(0, 3) = "item 0,3"
marray(1, 0) = "item 1,0"
marray(1, 1) = "item 1,1"
marray(1, 2) = "item 1,2"
marray(1, 3) = "item 1,3"
marray(2, 0) = "item 2,0"
marray(2, 1) = "item 2,1"
marray(2, 2) = "item 2,2"
marray(2, 3) = "item 2,3"

For Each item In marray
    WScript.Echo item
Next

ReDim Preserve marray(UBound(marray)+2, 3)
WScript.Echo "New marray ubound = " & UBound(marray)
marray(3, 0) = "item 3,0"
marray(3, 1) = "item 3,1"
marray(3, 2) = "item 3,2"
marray(3, 3) = "item 3,3"
marray(4, 0) = "item 4,0"
marray(4, 1) = "item 4,1"
marray(4, 2) = "item 4,2"
marray(4, 3) = "item 4,3"

For Each item In marray
    WScript.Echo item
Next

错误消息是:

  

arrays.vbs(19,1)Microsoft VBScript运行时错误:下标超出范围)

1 个答案:

答案 0 :(得分:1)

对于多维数组,您需要告诉UBound应该检查哪个维度。

>>> ReDim arr(2, 3)
>>> WScript.Echo UBound(arr, 1)
2
>>> WScript.Echo UBound(arr, 2)
3
>>> ReDim Preserve arr(UBound(arr, 1), UBound(arr, 2)+1)
>>> WScript.Echo UBound(arr, 1)
2
>>> WScript.Echo UBound(arr, 2)
4

另请注意,您只能更改多维数组的 last 维度(同时保留数据)。尝试更改其他尺寸会产生错误:

>>> ReDim arr(2, 3)
>>> ReDim Preserve arr(UBound(arr, 1)+1, UBound(arr, 2))
Subscript out of range (0x9)

来自documentation

  

说明

     

[...]

     

如果您使用Preserve关键字,则只能调整最后一个数组维度,并且根本无法更改维度数。 [...]

如果您需要能够更改多个维度,则需要锯齿状数组(数组数组):

>>> ReDim arr(2)
>>> WScript.Echo UBound(arr)
2
>>> arr(0) = Array()
>>> WScript.Echo UBound(arr(0))
-1
>>> ReDim Preserve arr(UBound(arr)+1)
>>> WScript.Echo UBound(arr)
3

请注意,使用锯齿状数组需要单独调整嵌套数组的大小,而不能直接执行。

>>> ReDim arr(2)
>>> arr(0) = Array()
>>> WScript.Echo UBound(arr(0))
-1
>>> ReDim Preserve arr(0)(UBound(arr(0))+1)  'this doesn't work!
Expected end of statement (0x401)
>>> tmp = arr(0)                             'need a temp variable
>>> ReDim Preserve tmp(UBound(tmp)+1)
>>> arr(0) = tmp
>>> WScript.Echo UBound(arr(0))
0