本文介绍如何使用 JScript 或 JavaScript 遍历集合。
原始产品版本: Visual Studio
原始 KB 数: 229693
总结
本文介绍如何在 Active Server Pages(ASP)页上使用服务器端脚本和 Visual Basic 脚本(VBScript)和 JScript 或 JavaScript 遍历集合。 在 VBScript 中,可以使用 FOR EACH...NEXT 循环遍历集合。 在 JScript 或 JavaScript 中,必须使用枚举器对象。
详细信息
本文中的示例使用文件系统对象遍历文件夹(在本例中), C:\Text并列出文件夹中的所有文件。 第一个 FOR EACH...NEXT 示例使用 VBScript 中的循环遍历:
- 在驱动器 C 的根文件夹中创建新文件夹,并将其命名为 Text。
- 将五个文本文件放置在创建的目录中。
- 创建新的 ASP 页并添加以下 VBScript 代码:
<% @LANGUAGE="VBScript" %>
<%
'Reference the FileSystemObject
set FSO = Server.CreateObject("Scripting.FileSystemObject")'Reference the Text directory
set Folder = FSO.GetFolder("C:\Text")'Reference the File collection of the Text directory
set FileCollection = Folder.Files
Response.Write("VBScript Method<BR>")'Display the number of files within the Text directory
Response.Write("Number of files found: " & FileCollection.Count & "<BR>")'Traverse through the FileCollection using the FOR EACH...NEXT loop
For Each FileName in FileCollection
strFileName = FileName.Name
Response.Write(strFileName & "<BR>")
Next
'De-reference all the objects
set FileCollection = Nothing
set Folder = Nothing
set FSO = Nothing
%>
以下示例演示等效项,但使用 JScript 或 JavaScript 和枚举器对象,如下所示。 按照前面概述的步骤进行操作,但步骤 3 中使用以下代码。
<% @LANGUAGE="JScript" %>
<%
// Reference the FileSystemObject
var FSO = Server.CreateObject("Scripting.FileSystemObject");
// Reference the Text directory
var Folder = FSO.GetFolder("c:\\Text");
// Reference the File collection of the Text directory
var FileCollection = Folder.Files;
Response.Write("JScript Method<BR>");
// Display the number of files within the Text directory
Response.Write("Number of files found: " + FileCollection.Count + "<BR>");
// Traverse through the FileCollection using the FOR loop
for(var objEnum = new Enumerator(FileCollection); !objEnum.atEnd(); objEnum.moveNext()) {
strFileName = objEnum.item();
Response.Write(strFileName + "<BR>");
}
// Destroy and de-reference enumerator object
delete objEnum;
objEnum = null;
// De-reference FileCollection and Folder object
FileCollection = null;
Folder = null;
// Destroy and de-reference FileSystemObject
delete FSO;
FSO = null;
%>
注意
枚举器对象在 FOR 循环中实例化,在 JScript 或 JavaScript 中是可以的。 FOR 语句的语法如下所示:
FOR(初始化; test; increment) 语句;
本文中每个示例的输出将以不同的方式显示。 在 VBScript 中,输出仅显示文件名及其文件扩展名,如下所示:
VBScript Method
Number of files found: 5
test1.txt
test2.txt
test3.txt
test4.txt
test5.txt
在 JScript 或 JavaScript 中,输出显示物理文件夹、文件名及其文件扩展名:
JScript Method
Number of files found: 5
C:\Text\test1.txt
C:\Text\test2.txt
C:\Text\test3.txt
C:\Text\test4.txt
C:\Text\test5.txt
本文中讨论的第三方产品由 Microsoft 以外的其他公司提供。 对于这些产品的性能或可靠性,Microsoft 不作任何暗示保证或其他形式的保证。
参考
有关 JScript 和 VBScript 的详细信息,请参阅 Windows 脚本技术简介。