我有2个阵列
array1 = Array("elem1", "elem2", "elem3")
array2 = Array("item1", "item2", "item3")
然后我选择其中一个数组
Randomize
dim refArray
if Rnd < 0.5 then
refArray = array1
else
refArray = array2
end if
我对其元素进行了更改
refArray(0) = "foo"
refArray(1) = "bar"
Say Rnd小于0.5并且refArray = array1执行。我希望array1和refArray都指向同一块内存,所以当我对refArray进行更改时,它们也应该在array1中可见。
代码执行后,我希望array1的内容为:&#34; foo&#34;,&#34; bar&#34;,&#34; elem3&#34;。但它保持不变。
我遇到的问题是vbs没有传递对array1或array2的引用,而是将它复制到一个新的数组refArray,它获取更改并使数组1和2保持不变。
如何获取对数组的引用并对refArray所做的更改是否适用于引用的对象(正常的Java / C用法)?
感谢。
答案 0 :(得分:2)
获取对本机VBScript数组的引用的唯一方法是Sub / Function调用:
>> Sub assignArray(a, i, e)
>> a(i) = e
>> End Sub
>> array1 = Array("elem1", "elem2", "elem3")
>> array2 = Array("item1", "item2", "item3")
>> WScript.Echo "array1", Join(array1), "array2", Join(array2)
>> assignArray array1, 0, "abra"
>> assignArray array2, 0, "cadabra"
>> WScript.Echo "array1", Join(array1), "array2", Join(array2)
>>
array1 elem1 elem2 elem3 array2 item1 item2 item3
array1 abra elem2 elem3 array2 cadabra item2 item3
如果这不能解决您的实际问题 - 顺便说一句: 你的真实问题是什么? - 考虑使用对象(Dictionary,System.Collections.ArrayList)。
拼出来:
数组分配副本。仅通过参数传递可以引用(本机)数组。由于VBscript既不是C也不是Java,你必须使你的'设计'适应语言 - 例如:
Option Explicit
Sub assignArray(a, i, e)
a(i) = e
End Sub
Randomize
Dim a1 : a1 = Split("I don't believe this")
Dim a2 : a2 = Split("solves any real-word problem")
WScript.Echo "a1:", Join(a1)
WScript.Echo "a2:", Join(a2)
If Rnd < 0.5 Then
assignArray a1, 0, "We"
Else
assignArray a2, 3, "problems"
End If
WScript.Echo "a1:", Join(a1)
WScript.Echo "a2:", Join(a2)
输出:
a1: I don't believe this
a2: solves any real-word problem
a1: We don't believe this
a2: solves any real-word problem
a1: I don't believe this
a2: solves any real-word problem
a1: I don't believe this
a2: solves any real-word problems
答案 1 :(得分:2)
如果您需要通过引用处理数组,请考虑使用ArrayList
对象:
>>> Set a1 = CreateObject("System.Collections.ArrayList")
>>> a1.Add 1
>>> a1.Add 2
>>> a1.Add 3
>>> WScript.Echo "[" & Join(a1.ToArray, ",") & "]"
[1,2,3]
>>> Set a2 = a1
>>> a2(1) = 4
>>> WScript.Echo "[" & Join(a2.ToArray, ",") & "]"
[1,4,3]
>>> WScript.Echo "[" & Join(a1.ToArray, ",") & "]"
[1,4,3]