What is the best way to iterate through an array in Classic Asp VBScript?

感情迁移 提交于 2020-06-22 13:25:51

问题


In the code below

For i = LBound(arr) To UBound(arr)

What is the point in asking using LBound? Surely that is always 0.


回答1:


Why not use For Each? That way you don't need to care what the LBound and UBound are.

Dim x, y, z
x = Array(1, 2, 3)

For Each y In x
    z = DoSomethingWith(y)
Next



回答2:


There is a good reason to NOT USE For i = LBound(arr) To UBound(arr)

dim arr(10) allocates eleven members of the array, 0 through 10 (assuming the VB6 default Option Base).

Many VB6 programmers assume the array is one-based, and never use the allocated arr(0). We can remove a potential source of bugs by using For i = 1 To UBound(arr) or For i = 0 To UBound(arr), because then it is clear whether arr(0) is being used.

For each makes a copy of each array element, rather than a pointer.

This has two problems.

  1. When we try to assign a value to an array element, it doesn't reflect on original. This code assigns a value of 47 to the variable i, but does not affect the elements of arr.

    arr = Array(3,4,8)
    for each i in arr
         i = 47
    next i
    Response.Write arr(0) '- returns 3, not 47
  2. We don't know the index of an array element in a for each, and we are not guaranteed the sequence of elements (although it seems to be in order.)




回答3:


LBound may not always be 0.

Whilst it is not possible to create an array that has anything other than a 0 Lower bound in VBScript, it is still possible to retrieve an array of variants from a COM component which may have specified a different LBound.

That said I've never come across one that has done anything like that.




回答4:


Probably it comes from VB6. Because with Option Base statement in VB6, you can alter the lower bound of arrays like this:

Option Base 1

Also in VB6, you can alter the lower bound of a specific array like this:

Dim myArray(4 To 42) As String



回答5:


I've always used For Each...




回答6:


This is my approach:

dim arrFormaA(15)
arrFormaA( 0 ) = "formaA_01.txt"
arrFormaA( 1 ) = "formaA_02.txt"
arrFormaA( 2 ) = "formaA_03.txt"
arrFormaA( 3 ) = "formaA_04.txt"
arrFormaA( 4 ) = "formaA_05.txt"
arrFormaA( 5 ) = "formaA_06.txt"
arrFormaA( 6 ) = "formaA_07.txt"
arrFormaA( 7 ) = "formaA_08.txt"
arrFormaA( 8 ) = "formaA_09.txt"
arrFormaA( 9 ) = "formaA_10.txt"
arrFormaA( 10 ) = "formaA_11.txt"
arrFormaA( 11 ) = "formaA_12.txt"
arrFormaA( 12 ) = "formaA_13.txt"
arrFormaA( 13 ) = "formaA_14.txt"
arrFormaA( 14 ) = "formaA_15.txt"

Wscript.echo(UBound(arrFormaA))
''displays "15"

For i = 0 To UBound(arrFormaA)-1
    Wscript.echo(arrFormaA(i))
Next

Hope it helps.



来源:https://stackoverflow.com/questions/2348/what-is-the-best-way-to-iterate-through-an-array-in-classic-asp-vbscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!