Enumerator 对象

启用集合中项的枚举。

varName = new Enumerator([collection])

实参

  • varName
    必选。 枚举数分配到的变量名称。

  • collection
    可选。 任何实现 IEnumerable 接口的对象,如数组或集合。

备注

每个集合在 JScript 中自动具有可枚举性。 因此,您不需要使用 Enumerator 对象来访问集合的成员。 您可以使用 for...in 语句来直接访问任何成员。 Enumerator 对象是为实现向后兼容性而提供的。

与数组不同,集合的成员不可以直接进行访问。 您不能像对于数组一样使用索引,而只能将当前项指针移动到集合的第一个或下一个元素。

Enumerator 对象提供了访问任何集合成员的方法,它的行为方式类似于 VBScript 中的 For...Each 语句。

您可以通过定义实现 IEnumerable 的类在 JScript 中创建集合。 也可以使用另一种语言(如 Visual Basic)或通过 ActiveXObject 对象来创建集合。

示例 1

以下代码使用 Enumerator 对象来输出可用驱动器的盘符及其名称(如果可用):

// Declare variables.
var n, x;
var fso : ActiveXObject = new ActiveXObject("Scripting.FileSystemObject");
// Create Enumerator on Drives.
var e : Enumerator = new Enumerator(fso.Drives);
for (;!e.atEnd();e.moveNext()) {      // Loop over the drives collection.
   x = e.item();
   if (x.DriveType == 3)              // See if network drive.
      n = x.ShareName;                // Get share name
   else if (x.IsReady)                // See if drive is ready.
      n = x.VolumeName;               // Get volume name.
   else
      n = "[Drive not ready]";
   print(x.DriveLetter + " - " + n);
}

根据系统的不同,输出将类似于下面这样:

A - [Drive not ready]
C - DRV1
D - BACKUP
E - [Drive not ready]

示例 2

示例 1 中代码可以进行改写,以便在不使用 Enumerator 对象的情况下使用。 在该示例中,将直接访问枚举的成员。

// Declare variables.
var n, x;
var fso : ActiveXObject = new ActiveXObject("Scripting.FileSystemObject");
// The following three lines are not needed.
//    var e : Enumerator = new Enumerator(fso.Drives);
//    for (;!e.atEnd();e.moveNext()) {
//       x = e.item();
// Access the members of the enumeration directly.
for (x in fso.Drives) {               // Loop over the drives collection.
   if (x.DriveType == 3)              // See if network drive.
      n = x.ShareName;                // Get share name
   else if (x.IsReady)                // See if drive is ready.
      n = x.VolumeName;               // Get volume name.
   else
      n = "[Drive not ready]";
   print(x.DriveLetter + " - " + n);
}

属性

Enumerator 对象没有属性。

方法

Enumerator 对象方法

要求

版本 3

请参见

参考

new 运算符

for...in 语句