了解VBScript中的对象和范围数组

时间:2016-08-25 17:39:52

标签: arrays vbscript scope

我编写了一个小程序来帮助我学习如何使用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

正如我们所看到的,最后一个对象是使用id为60创建的,以及一些数组的每个索引现在如何包含该对象。

1 个答案:

答案 0 :(得分:5)

您只有一个tObj可以连续分配Id编号。当你开始打印时,这个tObj保存最后一个Id。

如果你想(了解)对象数组(没有像globals,Call,Dim x()这样的暴行,或者数组大小/ UBound的错误/不理解),那么看看

Option Explicit

Class cX
  Public mnId
  Public Function ctor(nId)
    Set ctor = Me
    ctor.mnId = nId
  End Function
End Class

Sub printArrayofX(a)
  Dim i
  For i = 0 To UBound(a)
      Wscript.Echo a(i).mnId
  Next
End Sub

ReDim a(3)
Dim i
For i = 0 To UBound(a)
    Set a(i) = New cX.ctor(i)
Next

printArrayofX a

输出:

cscript 39151577-2.vbs
0
1
2
3