1

我有 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"

假设 Rnd 小于 0.5 并且 refArray = array1 执行。我希望 array1 和 refArray 都指向同一块内存,所以当我对 refArray 进行更改时,它们也应该在 array1 中可见。

代码执行后,我希望 array1 的内容为:“foo”、“bar”、“elem3”。但相反,它保持不变。

我遇到的问题是 vbs 没有传递对 array1 或 array2 的引用,而是将其复制到一个新的数组 refArray,该数组得到更改并使数组 1 和 2 保持不变。

如何获取对数组的引用并将对 refArray 所做的更改应用于引用的对象(正常的 Java/C 用法)?

谢谢。

4

2 回答 2

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

如果那不能解决您的实际问题-顺便说一句:您的实际问题什么?- 考虑改用对象(字典、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
于 2013-08-26T14:45:48.227 回答
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]
于 2013-08-27T14:13:34.873 回答