📜  VBScript-数组

📅  最后修改于: 2020-10-19 04:08:56             🧑  作者: Mango


什么是数组?

我们非常清楚变量是存储值的容器。有时,开发人员可以一次在单个变量中保留多个值。当一系列值存储在单个变量中时,则称为数组变量

数组声明

声明数组的方式与声明变量的方式相同,只不过声明数组变量使用括号。在下面的示例中,括号中提到了数组的大小。

'Method 1 : Using Dim
Dim arr1() 'Without Size

'Method 2 : Mentioning the Size
Dim arr2(5) 'Declared with size of 5

'Method 3 : using 'Array' Parameter
Dim arr3
arr3 = Array("apple","Orange","Grapes")
  • 尽管Array size表示为5,但由于数组索引从ZERO开始,它可以容纳6个值。

  • 数组索引不能为负。

  • VBScript数组可以在数组中存储任何类型的变量。因此,数组可以在单个数组变量中存储整数,字符串或字符。

将值分配给数组

通过针对要分配的每个值指定数组索引值,将值分配给数组。它可以是一个字符串。


   

将以上代码另存为.HTML并在Internet Explorer中执行后,将产生以下结果-

Value stored in Array index 0 : 1
Value stored in Array index 1 : VBScript
Value stored in Array index 2 : 100
Value stored in Array index 3 : 2.45
Value stored in Array index 4 : 7/10/2013
Value stored in Array index 5 : 12:45:00 PM

多维数组

数组不仅限于单个维度,而且最多可以包含60个维度。二维数组是最常用的数组。

在以下示例中,声明了具有3行4列的多维数组。


   

将以上代码另存为.HTML并在Internet Explorer中执行后,将产生以下结果-

Value stored in Array index : 0 , 1 : Orange
Value stored in Array index : 2 , 2 : coffee

Redim声明

ReDim语句用于声明动态数组变量以及分配或重新分配存储空间。

ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
  • Preserve-一个可选参数,用于在更改最后一个维度的大小时将数据保留在现有数组中。

  • varname-一个必需的参数,表示变量的名称,应遵循标准变量命名约定。

  • 下标-一个Required参数,它指示数组的大小。

在下面的示例中,一个数组已被重新定义,然后在更改数组的现有大小时保留其值。

–在调整比原来小的数组的大小时,消除的元素中的数据将丢失。


   

当我们将以上脚本另存为HTML并在Internet Explorer中执行时,它会产生以下结果。

XYZ
41.25
22
3
4
5
6
7

数组方法

VBScript中有各种内置函数,可帮助开发人员有效地处理数组。下面列出了与数组结合使用的所有方法。请单击方法名称以了解详细信息。

Function Description
LBound A Function, which returns an integer that corresponds to the smallest subscript of the given arrays.
UBound A Function, which returns an integer that corresponds to the Largest subscript of the given arrays.
Split A Function, which returns an array that contains a specified number of values. Splitted based on a Delimiter.
Join A Function, which returns a String that contains a specified number of substrings in an array. This is an exact opposite function of Split Method.
Filter A Function, which returns a zero based array that contains a subset of a string array based on a specific filter criteria.
IsArray A Function, which returns a boolean value that indicates whether or not the input variable is an array.
Erase A Function, which recovers the allocated memory for the array variables.