Constant是一个命名的内存位置,用于保存在脚本执行期间无法更改的值.如果用户尝试更改常量值,则脚本执行最终会出错.常量的声明方式与声明变量的方式相同.
[Public | Private] Const Constant_Name = Value
常量可以是Public或Private类型.使用公共或私人是可选的.公共常量可用于所有脚本和过程,而私有常量可在过程或类中使用.可以将任何值(例如数字,字符串或日期)分配给声明的常量.
在此示例中,pi的值为3.4,它在消息框中显示圆圈的区域.
<!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim intRadius intRadius = 20 const pi = 3.14 Area = pi*intRadius*intRadius Msgbox Area </script> </body> </html>
以下示例说明如何将字符串和日期值分配给常量.
<!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Const myString = "VBScript" Const myDate = #01/01/2050# Msgbox myString Msgbox myDate </script> </body> </html>
在下面的示例中,用户尝试更改常量值;因此,它最终会出现执行错误.
<!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim intRadius intRadius = 20 const pi = 3.14 pi = pi*pi 'pi VALUE CANNOT BE CHANGED.THROWS ERROR' Area = pi*intRadius*intRadius Msgbox Area </script> </body> </html>