how to put index variable in for ... in loop in local scope?

Go To StackoverFlow.com

1

Whenever I use a for ... in loop, the index variable of the loop always seems to be in the variables scope.
For example if I have a component with a method that uses this loop:

for(key in params){  
    writeOutput(key);  
}

The variable 'key' will be placed in the variables scope. If I already have declared a variables.key anywhere in the component, this value gets overwritten when I use this for ... in loop. What I actually need is something like this:

for(var key in params){
    writeOutput(key);
}

This however throws a parsing error.

Is there any way to put the for ... in index in a different scope then the variables scope?

2012-04-04 07:19
by jan
How about writing a simple for loop - Vikas 2012-04-04 07:27
for(var i=1; i<=arrayLen(values); i++) { //code }Vikas 2012-04-04 07:30
@Vikas because with for ... in you can loop over structures. In my example 'params' is a struct. I could still use a for loop by looping over the structKeyArray(params) array, but I was wondering if it could be done with a simple for ... i - jan 2012-04-04 07:55


10

The default scope inside CFCs is variables if you don't var beforehand.

You have to var the index outside the loop like so:-

var key = "";

for(key in params){
    writeOutput(key);
}

An alternative approach, to avoid varring everything within your functions, is to declare your variables within a "local" structure. In CF9 a local scope is built in but for CF8 or below do something like this:-

var local = structNew();

for(local.key in params){
  writeOutput(local.key);
}
2012-04-04 07:41
by James Buckingham
Thanks. I'll go with your first option. Seems more elegant then the second one - jan 2012-04-04 07:58
var local = structNew() (or shorthand {} CF8+ ) is good if you have lots of variables within a function. Saves you having to remember to var everything and stuff potentially "leaking" out. For the example above you're right, it's overkill - James Buckingham 2012-04-04 08:25


3

This syntax will work in ColdFusion 9 and higher:

for ( var key in params ){
    writeOutput( key );
}
2012-04-04 12:23
by Scott Stroz
I tried this syntax in 9.0.0 and got a syntax error. In what version have you used this? 9.0.1 perhaps - jan 2012-04-11 14:17
I cannot say with any certainty that this will work in 9.0.0. I am running 9.0.1 (as should everyone :D - Scott Stroz 2012-04-11 14:21
Ads