Arrays VBSCRIPT数组键

Arrays VBSCRIPT数组键,arrays,vbscript,Arrays,Vbscript,我对vbscript还比较陌生,我对Javascript比较熟悉,所以有点吃力。 谁能帮我一下吗 vbscript是否允许像我在下面的示例中那样使用命名数组键 例如,我有: Dim result(3) result(age) = 60 result(firstname) = "Tony" result(height) = 187 result(weight) = 76 msgbox("Age: " & result(age) & vbC

我对vbscript还比较陌生,我对Javascript比较熟悉,所以有点吃力。 谁能帮我一下吗

vbscript是否允许像我在下面的示例中那样使用命名数组键

例如,我有:

Dim result(3)
result(age)       = 60
result(firstname) = "Tony"
result(height)    = 187
result(weight)    = 76

msgbox("Age: "    & result(age)       & vbCr &_
       "Name: "   & result(firstname) & vbCr &_
       "Height: " & result(height)    & vbCr &_
       "Weight: " & result(weight)    )
生成的msgbox显示:

  Age: 76 
  Name: 76 
  Height: 76 
  Weight: 76 
这似乎将结果数组中的每个元素都分配给76,这 应仅指定给“权重”元素

发生这种情况是因为vbscript只接受整数作为键/ 数组的索引

非常感谢您的帮助

谢谢
Turgs

没有VBScript只允许整数索引。也就是说,您可以声明整数常量来提供所需的功能


如果需要命名数组(如上面的示例),则可能需要某种字典。

要实现此目的,需要使用脚本库中的字典对象:-

Dim result : Set result = CreateObject("Scripting.Dictionary")
result.Add "Age", 60
result.Add "Name", "Tony"
等等。您可以通过以下方式检索项目:-

Dim age : age = result("Age")

但是,如果你有固定的标识符集,你可以考虑定义一个类:-< /P>

Class CResult
    Public Age
    Public Name
End Class

Dim result : Set result = new CResult
result.Age = 60
result.Name = "Tony"

MsgBox "Age: "    & result.Age       & vbCrLf & _
   "Name: "   & result.Nname) & vbCrLf
顺便说一句,通常,我们对新行使用CR LF,而不仅仅是CR。此外,如果您使用方法或函数作为语句(如上面的MsgBox中所示),请不要将参数括在()中。

除了此页上的,我已经能够在VBScript中使用Dictionary对象来完成我在使用语法后所做的工作,该语法更像其他语言中正常使用的关联数组:

Dim result 
Set result = CreateObject("scripting.dictionary") 

result("age") = 60 
result("firstname") = "Tony" 
result("height") = 187 
result("weight") = 76 

msgbox("Age: "       & result("age")       & vbCr &_ 
      "First Name: " & result("firstname") & vbCr &_ 
      "Height: "     & result("height")    & vbCr &_ 
      "Weight: "     & result("weight")    ) 
有关dictionary对象的详细信息,请参见:

我希望这对其他尝试做同样事情的人有所帮助

感谢您通过microsoft.public.scripting.vbscript Usenet组提供此解决方案

干杯


Turgs

OP的代码实际上可以通过一个完整的黑客程序来工作。这一点很重要,因为一些老程序员已经使用了这种方法,这可能有助于学习这种技巧

因此,要使以下“标识符”发挥作用,即年龄/名/身高/体重:

result(age)
result(firstname) 
result(height)  
result(weight) 
黑客是将这些定义为变量或全局变量,以正确排序索引。当然,这可以通过编程实现:

'Creates variables that map the field name to its position in the Array.
Private Sub CreateArrayIdentifiersAsGlobalVariables(fieldNames)
    Dim globalVariablesToCreate
    Dim fieldNameIndex
    fieldNameIndex = 0
    For Each fieldName In fieldNames
        If Len(fieldName) > 0 Then
            globalVariablesToCreate = globalVariablesToCreate & "fieldName & "=" & fieldNameIndex & vbCrLf
            fieldNameIndex = fieldNameIndex + 1
        End If
    Next
    Execute globalVariablesToCreate
End Sub
其中“fieldNames”是所有字符串字段名的数组


所以你可以用数组“age,firstname,height,weight”来调用这个函数。然后,例如,您将“age”作为一个全局变量计算整数0,firstname作为1,然后“result(age)”和“result(firstname)”将按预期工作。

顺便说一句,您得到76的原因是,您所有的“key”都被解释为未定义的变量,这些变量的计算结果为零,没有任何警告。