Question

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.

Was it helpful?

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.

OTHER TIPS

In CF 10 and Railo 4, you could use the Underscore.cfc library.

_ = new Underscore();// instantiate the library

_.each(myArray, function(item, index) {
   // code here
});

Although personally, I'd rather use one of the other functional methods, such a map or reduce, depending on what you're trying to do.

Note: I wrote Underscore.cfc

You can use:

<cfscript>
    for (key in struct) {
        writeOutput("#key# = #struct[key]# <br>");
    }
</cfscript>

or

<cfoutput>
    <cfloop collection="#params#" item="key" >
        #key# = #params[key]#         
    </cfloop>
</cfoutput>

Remember to set "this.serialization.preservecaseforstructkey = true" in the Applicacion.cfc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top