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?
for(var i=1; i<=arrayLen(values); i++) {
//code
}
Vikas 2012-04-04 07:30
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);
}
This syntax will work in ColdFusion 9 and higher:
for ( var key in params ){
writeOutput( key );
}