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>
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With