How to tell whether a variable in ASP has been declared

此生再无相见时 提交于 2019-12-05 06:54:34

ust by the way, your question isn't about classic ASP, it is a VBScript question. VBScript can occur in scripts outside of ASP. And compilation isn't done in VBScript, because it is an interpreted language. Nevermind.

I think there's some confusion here -- and your question seems to have more to do with uninitialized variables than undeclared variables. For undeclared variables, see below.

For uninitialized, try the function IsEmpty. For checking for null, try the function IsNull.

dim x
x = 1
dim t
Response.write isempty(x)
Response.write "<br>"
Response.write isempty(t)   

Will display:

False

True

Detecting Undeclared Variables

If you include Option Explicit in your header, use of a non-declared variable will cause an runtime error. If your script is not Option Explicit it will not generate an error, and there is no function that will tell you if the variable has been declared or not. This sounds sloppy, and it is, but it was intentional.

The only way you can escape this is to actually set Option Explicit and then trap the error that you will get when you try to use the undeclared variable. If you trap this particular error you will find that it has Err.Number = 500. So, the following will do what you want:

Option Explicit

dim x

On Error Resume Next

Response.Write dsep_robots  
If Err.Number > 0 Then
    Response.Write Err.Number
end if

Of course, if you set Option Explicit and your code is rife with undeclared variables then you'll get errors being thrown all over the place, so you'd need to set On Error Resume Next at the top of your code so you can successfully ignore it, and only trap it when you want to.

By the way, here's Microsoft's online reference for VBScript:

http://msdn.microsoft.com/en-us/library/d1wf56tt(v=VS.85).aspx

@Jazzerus: I'd recommend putting the code within header.asp into a Sub, something like

Sub outputHeader(ByRef MyTitle, Byref dsep_robots)    
  'contents of header.asp
End Sub

...and then in your calling pages include header.asp right at the top and use

outputHeader "Title for this page", "value you want dsep_robots to have for page"

If you don't set dsep_robots on that page, then just leave the second parameter blank ("")

Then just checking if the variable is empty or not within the Sub should suffice:

If dsep_robots <> "" Then
  Response.Write dsep_robots
End If

What about:

 If NOT IsEmpty(myvariable) Then...

that seems to have been working for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!