Dynamic array in vbscript gets cleared when control comes out of loop

天涯浪子 提交于 2019-12-24 07:47:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!