How do I test to see if a variable exists in a ColdFusion struct?

Deadly 提交于 2019-12-23 07:34:23

问题


I would like to test:

<cfif Exists(MyStruct["mittens"])>
</cfif>

If the "mittens" key doesn't exist in MyStruct, what will it return? 0, or ""??

What should replace Exists function?

UPDATE

I tried,

<cfif IsDefined(MyStruct.mittens)>

Which also throws the error

Element Mittens is undefined in MyStruct.


回答1:


To test for key existence, I recommend:

<cfif StructKeyExists(MyStruct, "mittens")>

<!--- or --->

<cfset key = "mittens">
<cfif StructKeyExists(MyStruct, key)>

Behind the scenes this calls the containsKey() method of the java.util.map the ColdFusion struct is based on. This is arguably the fastest method of finding out if a key exists.

The alternative is:

<cfif IsDefined("MyStruct.mittens")>

<!--- or --->

<cfset key = "mittens">
<cfif IsDefined("MyStruct.#key#")>

Behind the scenes this calls Eval() on the passed string (or so I believe) and tells you if the result is a variable reference. In comparison this is slower than StructKeyExists(). On the plus side: You can test for a sub-key in a nested structure in one call:

<cfif IsDefined("MyStruct.with.some.deeply.nested.key")>



回答2:


Found the answer here

It's StructKeyExists



来源:https://stackoverflow.com/questions/771226/how-do-i-test-to-see-if-a-variable-exists-in-a-coldfusion-struct

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