Is:
For i = LBound(arr) To UBound(arr)
The best way?
What is the point in asking for LBound? Surely that is always 0 isn't it?
Is:
For i = LBound(arr) To UBound(arr)
The best way?
What is the point in asking for LBound? Surely that is always 0 isn't it?
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
Option Base doesn't seem to work in ASP
Yes it only does in VB6 like I said. My point is that this usage comes from VB6 programmers who are also ASP (VBScript) programmers.
There is a good reason NOT to 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). You 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. First, when you try to assign a value to an array element, it doesn't happen. This code assigns a value of 47 to the variable i, but does not affect the elements of arr.
for each i in arr
i = 47
next i
Second, you don't know the index of an array element in a "for each," and you are not guaranteed the sequence of elements (although it seems to be in order.)
LBound may not always be 0. Whilst it is not possible to create an array that has anything other than a 0 Lower bound 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.
It is actually a matter of taste. For i ... UBound is a tad faster, but ForEach is cleaner.