如何创建 VBScript 多行数组?

How do I create a VBScript multiline array?

我有一个我使用的 VBScript 文件,它在一个数组中有很多值。

recipes = Array("chicken soup","turkey","mash potatoes","yams","stuffing")

在多行上声明此数组的正确方法是什么,类似于:

recipes = Array("chicken soup",
"turkey",
"mash potatoes",
"yams",
"stuffing")

这样我就可以在每一行上写评论(或者这是正确的吗?):

recipes = Array("chicken soup", 'broth, noodles, chicken
"turkey",         'YUMMY i love turkey
"mash potatoes",  'butter, sour cream, cook 20mins
"yams",           'dont forget the marshmallows
"stuffing")       'celery, jiffy cornbread, broth

只需在每行末尾添加下划线,如下所示:

recipes = Array("chicken soup",_
                "turkey",_
                "mash potatoes",_
                "yams",_
                "stuffing")

注意:但即使在这种情况下,您也不能为每一行添加评论。

如果您想逐行声明数组值以允许注释,您有两种选择。

  1. 如果您有固定数量的数组项,您可以定义数组然后填充每个元素。

    Dim receipes(4)
    Dim receipe
    
    receipes(0) = "chicken soup"  'Chicken Soup
    receipes(1) = "turkey"        'Turkey
    receipes(2) = "mash potatoes" 'Mash Potatoes
    receipes(3) = "yams"          'Yams
    receipes(4) = "stuffing"      'Stuffing
    
    For Each receipe In receipes
      WScript.Echo receipe
    Next
    

    输出:

    chicken soup
    turkey
    mash potatoes
    yams
    stuffing
    
  2. 如果需要动态声明可以使用ReDimPreserve 关键字告诉 ReDim 在调整维度大小时不要清空数组。

    Dim receipe
    ReDim receipes(0)
    receipes(0) = "chicken soup"  'Chicken Soup
    ReDim Preserve receipes(1)
    receipes(1) = "turkey"        'Turkey
    ReDim Preserve receipes(2)
    receipes(2) = "mash potatoes" 'Mash Potatoes
    ReDim Preserve receipes(3)
    receipes(3) = "yams"          'Yams
    ReDim Preserve receipes(4)
    receipes(4) = "stuffing"      'Stuffing
    
    For Each receipe In receipes
      WScript.Echo receipe
    Next
    

    输出:

    chicken soup
    turkey
    mash potatoes
    yams
    stuffing
    

有用的链接

这是我最终使用的解决方案,感谢 Lankymart 推荐 ReDim,它完全符合我的要求。我可以有一个项目列表,这些项目被添加到可以完全注释掉或重新排列的数组中。出于我的目的,该代码用于一个小型实用程序,速度绝对不重要。

Dim recipe, recipes
ReDim recipes(0)

Function AddRecipe(v)
  If recipes(0) = "" Then
    recipes(UBound(recipes)) = v
  Else
    ReDim Preserve recipes(UBound(recipes)+1)
    recipes(UBound(recipes)) = v
  End If
End Function

AddRecipe("Ham")            'Honey Glazed
AddRecipe("turkey")         'YUMMY i love turkey
AddRecipe("mash potatoes")  'butter, sour cream, cook 20mins
AddRecipe("yams")           'dont forget the marshmallows
AddRecipe("stuffing")       'celery, jiffy cornbread, broth

For Each recipe In recipes
  WScript.Echo "value:" & recipe
Next

因为这个:

>> Sub Add2Array(a, v)
>>   ReDim Preserve a(UBound(a) + 1)
>>   a(UBound(a)) = v
>> End Sub
>> aa = Array()
>> WScript.Echo 0, TypeName(aa), UBound(aa)
>> Add2Array aa, "look, ma - one elm"
>> WScript.Echo 1, TypeName(aa), UBound(aa), aa(0)
>>
0 Variant() -1
1 Variant() 0 look, ma - one elm

差评。