ASP 变量

Dim 声明、Variant 类型、数组、作用域与生命周期。

Beginner
Key PointsVBScript 只有一种数据类型 Variant,声明用 Dim;变量在页面级、Sub 级、Session、Application 各有不同寿命。

声明与赋值

ASP
<%
    Dim name, age, price
    name = "Ada"
    age = 36
    price = 99.5

    Response.Write name & " / " & age & " / " & price
%>
Output
Ada / 36 / 99.5

Variant 类型

Every VBScript variable is a Variant whose subtype follows the assigned value (string, integer, date, boolean…). Convenient, but type errors surface only at runtime.

ASP
<%
    Dim v
    v = "10"
    Response.Write TypeName(v) & "<br>"        ' String

    v = 10
    Response.Write TypeName(v) & "<br>"        ' Integer

    v = 10.5
    Response.Write TypeName(v) & "<br>"        ' Double

    v = Now()
    Response.Write TypeName(v) & "<br>"        ' Date

    v = True
    Response.Write TypeName(v) & "<br>"        ' Boolean
%>
Output
String
Integer
Double
Date
Boolean

类型转换

ASP
<%
    Response.Write CStr(123) & "<br>"          ' "123"
    Response.Write CInt("42") + 1 & "<br>"     ' 43
    Response.Write CLng("9999999999") & "<br>"
    Response.Write CDbl("3.14") * 2 & "<br>"
    Response.Write CDate("2026-11-03") & "<br>"
    Response.Write IsNumeric("abc") & "<br>"   ' False
%>
Output
123
43
9999999999
6.28
2026/11/3
False

Values from Request are always strings. Convert with CInt/CDbl before arithmetic; guard with IsNumeric to avoid type-mismatch errors.

数组

ASP
<%
    Dim langs(2)                     ' 下标 0..2,共 3 个元素
    langs(0) = "VBScript"
    langs(1) = "JScript"
    langs(2) = "Perl"

    Dim i
    For i = 0 To UBound(langs)
        Response.Write langs(i) & "<br>"
    Next

    ' 动态数组
    Dim dyn()
    ReDim dyn(5)
    dyn(0) = "a"
    ReDim Preserve dyn(10)           ' 保留已有元素,扩容
%>
Output
VBScript
JScript
Perl

Dim a(2) declares three elements (0, 1, 2), not two. ReDim clears the data unless you add Preserve, and Preserve can only change the last dimension.

四种作用域

ScopeLifetimeDeclared by
Page一次请求页面顶部 Dim
Procedure一次调用Sub / Function 内 Dim
Session一个用户的一次访问期Session("x") = ...
Application站点启动到停止Application("x") = ...
Page-level variables die with the request. To survive across pages use Session or Application; to share across users only Application or a database works.

Friends & Partners