标量和数组变量

在大多数情况下,声明变量后,只会为其赋单个值。包含单个值的变量是标量变量。其他时候,为单个变量赋多个相关值会很方便。您可以创建一个可包含一系列值的变量。这称为数组变量。数组变量和标量变量的声明方式相同,只是数组变量的声明会在变量名称后使用括号 ( )

在以下示例中,声明了一个包含 11 个元素的单维数组:

Dim A(10)

虽然括号中显示的数字为 10,但 BSL 中的所有数组都是零基数。因此,此数组包含 11 个元素。在基于零的数组中,数组元素的数量始终是括号中显示的数字加一。这种数组称为固定大小的数组。

可以使用数组中的索引向数组的每个元素赋予数据。从零开始到 10 结束,可以按如下方式将数据赋给数组的元素:

     A(0) = 256
        A(1) = 324
        A(2) = 100
         . . .
        A(10) = 55

同样,可以使用所需数组元素中的索引从任何元素检索数据。

例如:

SomeVariable = A(8)

数组不限于单个维。可以通过在括号中使用逗号分隔数组的大小数值来声明多个维。在以下示例中,MyTable 变量是一个由 6 行 11 列组成的二维数组:

Dim MyTable(5,10)

在二维数组中,第一个数值始终是行数;第二个数值是列数。

您还可以声明一个其大小在脚本运行期间发生变化的数组。这称为动态数组。该数组最初是在过程中使用 Dim 语句或 ReDim 语句声明的。但是,对于动态数组,括号内不包含大小或维数。

例如:

Dim MyArray()
ReDim AnotherArray() ' Illegal as no dimension specified
ReDim AnotherArray(3)

要使用动态数组,随后必须使用 ReDim 来确定维数和每个维的大小。在以下示例中,ReDim 将动态数组的初始大小设置为 25。后续的 ReDim 语句将数组大小调整为 30,但使用 Preserve 关键字在调整大小时保留数组的内容。

ReDim MyArray(25)
 . . . 
ReDim Preserve MyArray(30)

您可以调整动态数组大小的次数没有限制,但如果使数组变小,则会丢失已消除元素中的数据。

以下示例说明了标量变量和数组变量的用法:

示例 1

Dim B
B = 200   ' Assigns the value 200 to the variable B.

示例 2

Dim A(3)   ' Declares a single-dimension array with 4 elements 0 to 3 indexes.
' Assigning values to each element of the array.
A(0) = 256
A(1) = 324
A(2) = 100
' Retrieving a value from the array.
Dim SomeVariable
SomeVariable = A(1)   ' Retrieves the value at index 1.

示例 3

Dim MyArray()   ' Declares a dynamic array.
ReDim MyArray(25)   ' Sets the initial size of the dynamic array to 25 elements.
' Assigning values to the dynamic array.
MyArray(0) = "First"
MyArray(25) = "Last"
' Resizing the dynamic array and preserving contents.
ReDim Preserve MyArray(30)   ' Resizes the array to 30 elements and preserves existing data.

示例 4

Dim AnotherArray()
ReDim AnotherArray(10)   ' Initial size of 10 elements.
' Assigning values to the array.
AnotherArray(0) = "Alpha"
AnotherArray(10) = "Omega"

' Resizing the array multiple times.
ReDim Preserve AnotherArray(20)
AnotherArray(20) = "NewElement"
ReDim Preserve AnotherArray(5)   ' Reduces the size of the array (data beyond index 5 is lost).