Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ColdFusion: Is it possible to get the index from a cfscript for in loop?

So I'm iterating through an array of structs using a for in loop

for(item in array) {
    processStruct(item)
}

Pretty straightforward, What I'm trying to do is get the current index in the for in loop and pass it along as well to the function: processStruct(item, index). I know I can do this with a regular for loop and it's also possible with the tag version <cfloop>

<cfloop array="#myArray#" index="i">
    #i#
<cfloop>
like image 980
Noe Avatar asked Feb 01 '26 05:02

Noe


2 Answers

The tag variant <cfloop> offers item and index starting with ColdFusion 2016 (or Railo/Lucee).

<cfset x = [ "a", "b", "c" ]>
<cfloop array="#x#" index="idx" item="it">
    <cfoutput>#idx#:#it#</cfoutput>
</cfloop>
<!--- returns 1:a 2:b 3:c --->

All ColdFusion versions prior to 2016 do not, so you would have to do it by yourself:

<cfset x = [ "a", "b", "c" ]>
<cfset idx = 1>
<cfloop array="#x#" index="it">
    <cfoutput>#idx#:#it#</cfoutput>
    <cfset idx++>
</cfloop>
<!--- returns 1:a 2:b 3:c --->

The script variant doesn't support it and most likely never will. Java's Iterator interface doesn't offer it either.

like image 131
Alex Avatar answered Feb 03 '26 10:02

Alex


As of CF11 you can use a member function. That way you have access to both the element and the index:

myArray = ["a", "b", "c"];
// By arrayEach() member function CF11+
myArray.each(function(element, index) {
    writeOuput(element & " : " & index);
});
like image 21
Chris Avatar answered Feb 03 '26 08:02

Chris