在經典 ASP 的 JScript (Microsoft JScript 5.x) 環境中,Request.QueryString 與 Request.Form 是類陣列集合,無法直接用 for...in 或 forEach 遍歷。正確做法是使用 Enumerator 物件。
<%@ Language=JScript %>
<%
var params = new Enumerator(Request.QueryString);
while (!params.atEnd()) {
var key = params.item();
var value = Request.QueryString(key);
Response.Write(key + " = " + value + "<br/>");
params.moveNext();
}
%>
new Enumerator(collection):建立列舉器。atEnd():是否到達集合末尾。item():取得當前項目(此處為鍵名)。moveNext():移至下一項。Request.QueryString(key),而非 params.item() 的值(後者僅回傳鍵名)。function dumpCollection(col, label) {
Response.Write("<h3>" + label + "</h3><pre>");
var e = new Enumerator(col);
while (!e.atEnd()) {
var k = e.item();
var v = col(k); // 關鍵:用集合本身索引取值
Response.Write(k + " = " + v + "\n");
e.moveNext();
}
Response.Write("</pre>");
}
dumpCollection(Request.QueryString, "QueryString");
dumpCollection(Request.Form, "Form");
// 錯誤!Request 不是集合,無法列舉
var params = new Enumerator(Request); // TypeError: Object doesn't support this property or method
Request 物件包含 QueryString、Form、Cookies、ServerVariables 等子集合,必須針對各子集合個別列舉。
Request.CookiesRequest.ServerVariablesSession.Contents / Session.StaticObjectsApplication.Contents / Application.StaticObjectsRecordset.Fields皆可用相同 Enumerator 模式遍歷。
掌握 Enumerator 模式,即可在 JScript ASP 中靈活檢查、除錯所有集合型物件,是經典 ASP 開發者的必備技能。