ColdFusion: select the first nonzero value from the list

In JavaScript, you can do this:

var a = null;
var b = "I'm a value";
var c = null;
var result = a || b || c;

And the "result" will get the value "b" because JavaScript shorts the "or" operator.

I want ColdFusion to execute a one-line idiom, and the best I can come up with is:

<cfif LEN(c) GT 0><cfset result=c></cfif>
<cfif LEN(b) GT 0><cfset result=b></cfif>
<cfif LEN(a) GT 0><cfset result=a></cfif>

Can anyone better than this?

+3
source share
2 answers

ColdFusion has no zeros.

Your example uses a selection by which the element is an empty string.

If this is what you need and all your other values ​​are simple values, you can do this:

<cfset result = ListFirst( "#a#,#b#,#c#" )/>

(This works because the standard list functions ignore empty elements.)

+8
source

: CFML- .

nulls ( ), , Railo OpenBlueDragon:

<cffunction name="FirstNotNull" returntype="any" output="false">
    <cfset var i = 0/>
    <cfloop index="i" from="1" to="#ArrayLen(Arguments)#">
        <cfif NOT isNull(Arguments[i]) >
            <cfreturn Arguments[i] />
        </cfif>
    </cfloop>
</cffunction>

, :

<cfset result = FirstNotNull( a , b , c ) />
+1

Source: https://habr.com/ru/post/1697752/


All Articles