Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In the code below

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

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

like image 683
Ronnie Avatar asked Aug 05 '08 14:08

Ronnie


People also ask

Which loop is best to work with collections in VBScript?

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.

What is an array in VBScript?

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.

What is iterate array?

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.


2 Answers

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 
like image 95
Chris Farmer Avatar answered Sep 19 '22 09:09

Chris Farmer


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.

  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 for each, and we are not guaranteed the sequence of elements (although it seems to be in order).

like image 33
xpda Avatar answered Sep 21 '22 09:09

xpda