【发布时间】:2017-01-02 06:10:51
【问题描述】:
我编写了一个小程序来帮助我学习如何在 VBScript 中使用对象数组,但我得到了一些不太有意义的结果。我不明白为什么当我打印出来时整个数组都被最后一个对象条目填满了。
Class TestObj
Public id
End Class
Dim arr()
Set tObj = new TestObj
Public Function fillArray()
ReDim arr(10)
For i = 0 To 9 Step 1
Call createObj()
Set arr(i) = tObj
Next
'Print the array in this function
Print ("Printing from fillArray function")
For i = 0 To 9 Step 1
Print ("arr("&i&"):"& arr(i).id)
Next
Call printArray()
End Function
Public Function createObj()
max = 100
min = 1
Randomize
randInt = (int((max-min+1)*Rnd+min))
Print ("Random Integer is: " &randInt)
tObj.id = randInt
End Function
Public Function printArray()
size = UBound(arr)
Print ("Printing from printArray function")
For i = 0 To size-1 Step 1
Print ("arr("&i&"):"& arr(i).id)
Next
End Function
Call fillArray()
输出如下:
Random Integer is: 80
Random Integer is: 92
Random Integer is: 70
Random Integer is: 10
Random Integer is: 18
Random Integer is: 100
Random Integer is: 27
Random Integer is: 47
Random Integer is: 34
Random Integer is: 60
Printing from fillArray function
arr(0):60
arr(1):60
arr(2):60
arr(3):60
arr(4):60
arr(5):60
arr(6):60
arr(7):60
arr(8):60
arr(9):60
Printing from printArray function
arr(0):60
arr(1):60
arr(2):60
arr(3):60
arr(4):60
arr(5):60
arr(6):60
arr(7):60
arr(8):60
arr(9):60
所以我们可以看到,最后一个对象是用 60 的 id 创建的,并且数组的每个索引现在都包含该对象。
【问题讨论】: