如何在ColdFusion中检查变量是否已定义

Har*_*ngh -2 coldfusion

我想在ColdFusion中使用if条件,它#firstWordCategory#是否定义了检查变量.

Beg*_*ner 7

每个变量都在某个范围内,而且(大多数)只是一个结构.

所以,你可以structKeyExists()像这样使用:

<!--- If your variable is in VARIABLES scope --->
<cfif structKeyExists(VARIABLES, "firstWordCategory")>

    <!--- Your Code --->

</cfif>
Run Code Online (Sandbox Code Playgroud)

  • OP没有指定范围,因此它被假定为在"VARIABLES"范围内,如注释中所述:`<!---如果你的变量在VARIABLES范围内--->`.试试这个:`<cfoutput> IsDefined"myVar1":#test1()#<br> StructKeyExists"myVar2":#test2()#</ cfoutput> <cffunction name ="test1"> <cfset var myVar1 =""> <cfreturn isDefined("myVar1")> </ cffunction> <cffunction name ="test2"> <cfset LOCAL.myVar2 =""> <cfreturn structKeyExists(LOCAL,"myVar2")> </ cffunction>` (2认同)

小智 5

要检查任何变量是否存在,可以使用isDefined函数:

<cfif isDefined("firstWordCategory")>
    <cfoutput>#firstWordCategory#</cfoutput>
</cfif>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请检查