共用方式為


Enumerator 物件

啟用列舉集合中項目的功能。

varName = new Enumerator([collection])

引數

  • varName
    必要項。 要設定列舉值的變數名稱。

  • collection
    選擇項。 實作 IEnumerable 介面的任何物件,例如陣列或集合物件。

備註

每個集合物件在 JScript 裡都是可以自動列舉的。 因此,您不需要使用 Enumerator 物件來存取集合物件的成員。 您可以使用 for...in 陳述式直接存取任何成員。 Enumerator 物件是為了回溯相容性 (Backward Compatibility) 而提供的。

集合物件不同於陣列的地方在於集合物件的成員不是直接存取的。 不像您在使用陣列時使用索引,您只能將目前項目指標移至集合物件的第一個或下一個元素。

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 物件也能作用。 在這裡,列舉型別 (Enumeration) 的成員可以直接存取。

// 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 陳述式