VBScript Tutorials - Herong's Tutorial Notes
Dr. Herong Yang, Version 4.01

Array Declaration and Built-in Functions

Part:   1  2   3  4  5 

VB Script Tutorials - Herong's Tutorial Notes © Dr. Herong Yang

Data Types and Literals

Variables

Logic Operations

String Operations

Conditional Statements

Arrays

Loop Statements

Functions and Subroutines

Built-in Functions

Variable Inspection

... Table of Contents

(Continued from previous part...)

Assigning Values to Array Elements

New values can be assigned to individual elements in an array using assignment statements like this:

   array_variable(index) = new_value

where "index" is the index value of an element the array associated with "array_variable", and "new_value" is the new value to be assigned the array element. The data type of the new value must match the array data type.

Retrieving Values from Array Elements

Retrieving values from array elements can done through their indexes like this:

   ... = ... array_variable(index) ...

VB also offers a special loop statement, "For Each" statement, to retrieve every element in an array like this:

   For Each element_variable In array_variable
      ... = ... element_variable ...
   Next

This statement will iterate through every element in the specified array. At each interation, The value of the current element will be copied to the specified temporary variable, "element_variable". The order of iteration is based on element index values from the lower bound to the upper bound.

Fixed-Size Array Example

To show you how fixed size array works, I wrote the following example, array_fixed_size.html:

<html>
<body>
<!-- array_fixed_size.html
   Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
   document.writeln("")
   Dim aWeek(6) 
   document.writeln("Is aWeek an array? " & IsArray(aWeek))

   aWeek(0) = "Sun"
   aWeek(4) = "Thu"
   aWeek(6) = "Sat"
   aWeek(1) = "Mon"

   document.writeln("Days in a week:")
   For i=LBound(aWeek) To UBound(aWeek)
      document.writeln("   " & i & " = " & aWeek(i))
   Next

'   aWeek(10) = "Abc"   'Error 1: Subscription out of range

'   ReDim Preserve aWeek(10) 'Error 2: This array is fixed

</script>
</pre>
</body>
</html>

Here is the output:

Is aWeek an array? True
Days in a week:
   0 = Sun
   1 = Mon
   2 = 
   3 = 
   4 = Thu
   5 = 
   6 = Sat

Note that there are two errors commented out in the example:

  • Error 1 - Array index (subscription) must be in the range of lower bound and upper bound.
  • Error 2 - Fixed-size array can not be resized with "ReDim" statements.

(Continued on next part...)

Part:   1  2   3  4  5 

Dr. Herong Yang, updated in 2006
VBScript Tutorials - Herong's Tutorial Notes - Array Declaration and Built-in Functions