问题
I am newbie to VBScript. I am trying my hands at Dynamic array concept in VBScript below is my code. Code:
dim arr()
For i = 0 To 3
Redim arr(i+1,2)
arr(i,0)=i
arr(i,1)=i+1
MsgBox arr(i,0)&"-"&arr(i,1)
Next
For i = 0 To UBound(arr)
MsgBox arr(i,0)&" "&arr(i,1)
Next
As soon as the control comes into second loop all the values stored in arr are lost. i do not understand why and how? I've tried adding Preserve keyword but it throws subscript out of range error. TIA!!!
回答1:
[oops, missed the two dimensions]
Use ReDim Preserve
instead of plain ReDim
. (And get rid of the () in the Dim
statement.)
[/oops]
You can only grow dynamic arrays (not fixed arrays Dimmed with (n[,m,..])). A more dimensional array can only grow the last dimension (docs). So:
Option Explicit
ReDim arr(1, -1) ' <-- dynamic
Dim i
For i = 0 To 3
ReDim Preserve arr(1, i) ' last dim grows
arr(0, i) = i
arr(1, i) = i + 1
Next
For i = 0 To 3
WScript.Echo i & ":", arr(0, i), arr(1, i)
Next
output:
cscript 29520636.vbs
0 0 1
1 1 2
2 2 3
3 3 4
来源:https://stackoverflow.com/questions/29520636/dynamic-array-in-vbscript-gets-cleared-when-control-comes-out-of-loop