【问题标题】:Understanding arrays of objects and scope in VBScript了解 VBScript 中的对象数组和范围
【发布时间】: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 创建的,并且数组的每个索引现在都包含该对象。

【问题讨论】:

    标签: arrays vbscript scope


    【解决方案1】:

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

    如果您想(了解)对象数组(没有诸如全局变量、调用、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
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2011-11-03
      • 2019-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      相关资源
      最近更新 更多