我正在寻找一种在VBS中存储数据的方法,如
[ 0 => [posX, posY], 1 => [posX, posY] ]
有点坐标为值的关联数组。
答案 0 :(得分:5)
关联数组在VBScript中称为Dictionary
。您可以像这样存储坐标:
Set coords = CreateObject("Scripting.Dictionary")
coords.Add 1, Array(1, 5)
coords.Add 2, Array(3, 2)
WScript.Echo coords(1)(1) 'ouput: 5
WScript.Echo coords(2)(0) 'ouput: 3
话虽如此,根据您的示例,您可能想要创建一个字典数组而不是数组字典:
Sub AddCoordinates(ByRef list, posX, posY)
Set d = CreateObject("Scripting.Dictionary")
d.Add "posX", posX
d.Add "posY", posX
ReDim Preserve list(UBound(list)+1)
Set list(UBound(list)) = d
End Sub
ReDim coords(-1)
AddCoordinates(coords, 1, 5)
AddCoordinates(coords, 3, 2)
...
WScript.Echo coords(0)("posY") 'ouput: 5
WScript.Echo coords(1)("posX") 'ouput: 3
自定义对象数组将是另一种选择:
Class Point
Private posX_
Private posY_
Public Property Get posX
posX = posX_
End Property
Public Property Let posX(val)
posX_ = val
End Property
Public Property Get posY
posY = posY_
End Property
Public Property Let posY(val)
posY_ = val
End Property
End Class
Sub AddCoordinates(ByRef list, posX, posY)
Set p = New Point
p.posX = posX
p.posY = posX
ReDim Preserve list(UBound(list)+1)
Set list(UBound(list)) = p
End Sub
ReDim coords(-1)
AddCoordinates(coords, 1, 5)
AddCoordinates(coords, 3, 2)
...
WScript.Echo coords(0).posY 'ouput: 5
WScript.Echo coords(1).posX 'ouput: 3
答案 1 :(得分:1)
当然,像这样。 字典是vbscript的键值解决方案。
Set objDictionary = CreateObject("scripting.dictionary")
objDictionary.Add 0, Array(1, 2)
objDictionary.Add 1, Array(3, 4)
WScript.Echo join(objDictionary.item(0)) '=>1 2'
像其他人评论的那样,vbscript已经不再使用了。 这是一个像Ruby
这样的更新语言的例子hash = {}
hash[0] = [1, 2]
hash[1] = [3, 4]
# gives {0=>[1, 2], 1=>[3, 4]}
或作为一行
Hash.new{}.merge(0 => [1, 2], 1 => [3, 4])
# gives {0=>[1, 2], 1=>[3, 4]}