如何测试ColdFusion结构中是否存在变量?

时间:2021-09-27 07:08:02

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 ""??

如果MyStruct中不存在“连指手套”键,它会返回什么? 0,还是“”?

What should replace Exists function?

什么应该取代存在的功能?

UPDATE

I tried,

<cfif IsDefined(MyStruct.mittens)>

Which also throws the error

这也引发了错误

Element Mittens is undefined in MyStruct.

元素手套在MyStruct中未定义。

2 个解决方案

#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.

在幕后,这将调用ColdFusion结构所基于的java.util.map的containsKey()方法。这可以说是找出密钥是否存在的最快方法。

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:

在幕后,它在传递的字符串上调用Eval()(或者我相信),并告诉你结果是否是变量引用。相比之下,这比StructKeyExists()慢。从好的方面来说:您可以在一次调用中测试嵌套结构中的子键:

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

#2


Found the answer here

在这里找到答案

It's StructKeyExists

#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.

在幕后,这将调用ColdFusion结构所基于的java.util.map的containsKey()方法。这可以说是找出密钥是否存在的最快方法。

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:

在幕后,它在传递的字符串上调用Eval()(或者我相信),并告诉你结果是否是变量引用。相比之下,这比StructKeyExists()慢。从好的方面来说:您可以在一次调用中测试嵌套结构中的子键:

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

#2


Found the answer here

在这里找到答案

It's StructKeyExists