coldfusionrailocfml

ColdFusion - Collection loop in cfscript


I have some tag based syntax that works in Railo.

<cfloop collection="#myArray#" item="j" index="i"></cfloop>

The above allows me to access the index 'i' and the item itself, 'j'.

I want to do the same in cfscript, so I used:

for ( i in myArray) {}

However, 'i' gives me the item...how can I access the index value?

As a work-around, I have had to manually count an index like so:

j = 1;
for ( i in myArray) {
j++;
}

But this feels dirty. Does the for in syntax of cfscript allow for a true alternative to cfloop's collection?

I have tried Google searching all of this but never get any decent result. Is there a way to rewrite my for in loop to allow me access to the index too?

Thanks, Mikey.


Solution

  • It's not possible in ColdFusion, I'm afraid, other than the work-around you are currently using, or just using an indexed for loop.

    However in Railo, there is this (rather awful tag/script hybrid syntax):

    <cfscript>
        loop array=[5,4,3,2,1] index="i" item="v"  {
            writeOutput("[#i#][#v#]<br>");
        }   
    </cfscript>
    

    So basically it's the <cfloop> without the angle brackets.