当控制退出循环时,vbscript 中的动态数组被清除 [英] Dynamic array in vbscript gets cleared when control comes out of loop
问题描述
我是 VBScript 的新手.我正在尝试使用 VBScript 中的动态数组概念,下面是我的代码.代码:
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
一旦控制进入第二个循环,所有存储在 arr 中的值都将丢失.我不明白为什么以及如何?我试过添加 Preserve 关键字,但它抛出下标超出范围错误.TIA!!!
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!!!
推荐答案
[哎呀,漏掉了两个维度]使用 ReDim Preserve
而不是普通的 ReDim
.(并去掉 Dim
语句中的 ().)[/哎呀]
[oops, missed the two dimensions]
Use ReDim Preserve
instead of plain ReDim
. (And get rid of the () in the Dim
statement.)
[/oops]
您只能增长动态数组(不是用 (n[,m,..]) 变暗的固定数组).多维数组只能增长最后一维(文档).所以:
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:
选项显式
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
输出:
cscript 29520636.vbs
0 0 1
1 1 2
2 2 3
3 3 4
这篇关于当控制退出循环时,vbscript 中的动态数组被清除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!