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.

Answers


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.


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


Need Your Help

Commons CLI is not honoring my command line setup

java command-line-interface apache-commons-cli

Using Apache Commons CLI 1.2 here. I have an executable JAR that needs to take 2 runtime options, fizz and buzz; both are strings that require arguments/values. I would like (if at all possible) my...

Entity Framework Specification Pattern Implementation

c# design-patterns entity-framework

How-to implement Specification Pattern with Entity Framework ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.