In the code below
For i = LBound(arr) To UBound(arr)
What is the point in asking using LBound
? Surely that is always 0.
A For Each loop is used when we want to execute a statement or a group of statements for each element in an array or collection. A For Each loop is similar to For Loop; however, the loop is executed for each element in an array or group.
VBScript Arrays can store any type of variable in an array. Hence, an array can store an integer, string or characters in a single array variable.
Iterating over an array means accessing each element of array one by one. There may be many ways of iterating over an array in Java, below are some simple ways. Method 1: Using for loop: This is the simplest of all where we just have to use a for loop where a counter variable accesses each element one by one.
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
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)
. We can remove a potential source of bug 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.
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
We don't know the index of an array element in for each
, and we are not guaranteed the sequence of elements (although it seems to be in order).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With