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?
The default scope inside CFCs is variables if you don’t var beforehand.
You have to var the index outside the loop like so:-
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:-