开发者

Dynamic arrays in VBScript with Split(). Is there a better way?

开发者 https://www.devze.com 2023-01-11 04:29 出处:网络
A lot of the scripts I write at my job depend on the creation of dynamically-sizable arrays. Arrays in VBScript make this a pretty arduous task, as one has to Redim arrays every time one wants开发者_C

A lot of the scripts I write at my job depend on the creation of dynamically-sizable arrays. Arrays in VBScript make this a pretty arduous task, as one has to Redim arrays every time one wants开发者_C百科 to resize them. To work around this, I've started making comma-delimited strings and using Split(...) to create 1D arrays out of it. While this works fantastic for me, I've wondered whether VBScript has a more efficient way of handling this. So I ask StackOverflow; are there?

Disclaimer: I'm fully aware that VBScript is a pretty substandard scripting language, but Python requires extra software, which is a bit of a hassle for server automation, and PowerShell isn't a core component yet. I'm learning them both, though!


The solution I usually go for is to resize the array each time I add new item to it. In that way the end array will never have any unused entries.

ReDim aArray(-1)

For i = 1 To 10
    ReDim Preserve aArray(UBound(aArray) + 1)
    aArray(UBound(aArray)) = i
Next

MsgBox Join(aArray, "," & vbNewLine)

Other solution proposed by Carlos is to do it using Dictionary object which is probably cleaner solution:

Set dic = CreateObject("Scripting.Dictionary")

dic.Add "Item1", ""
dic.Add "Item2", ""
dic.Add "Item3", ""

msgbox Join(dic.Keys, "," & vbNewLine)

Thanks, Maciej


How about a Dictionary object?

0

精彩评论

暂无评论...
验证码 换一张
取 消