When is an array not an array

posted by Chris on May 11, 2011 at 14:00

Coldfusion 9.0.1 added for-in looping over arrays, which is great, it's much simpler and a lot less verbose than having to iterate over with an index.  

<cfscript>
for(item in myarray) {
  doSomething(item);
}
</cfscript>

 

While writing a little bit of code to loop over properties in a Coldfusion ORM cfc, naturally i used the for-in syntax. Here's the basics of what i wanted to do;

<cfscript>
public void function postLoad( any entity ) {
  var md = getMetaData(this);
  for(var p in md.properties) {
    doSomething(p);
  }
}
</cfscript>

But CF wasn't having any of it and threw me an error.

coldfusion.runtime.ScopeCastException: You have attempted to dereference a scalar variable of type class [Ljava.lang.Object; as a structure with members.

cfc-properties

 

As you can see the md.properties key definetely looks like an array when you cfdump it, however its java type is not a coldfusion.runtime.Array, its a java.lang.Object[] and while cfdump is happy to make it look like an array, it seems that this is incompatible with the for-in array syntax

 

Its a shame to find little inconsistencies like this, whilst it doesn't impact on the functionality because you can easily work around by using index based looping, its just another quirk to remember and i've only got limited space to remember these things!

 

There is a bug report filed on cfbugs for this issue

Comments

todd sharp on May 11, 2011 at 14:17
Don't forget to var scope p in your second code example :) I know it's just a demo - but var scoping is super important and some folks may not realize you can do it in the for statement:

for(var p in md.properties){};
Chris on May 11, 2011 at 18:48
Nice catch Todd, now that CFBuilder 2 is out you can actually use that syntax without breaking syntax highlighting for everything that follows :)
betathomebonus on Aug 12, 2011 at 14:27
chris.m0nk3y.net is bookmarked for future reference!
[url=http://www.facebook.com/pages/Betathome-new-promotions/263682786990966]betathome[/url]
Camden Chronicle on Aug 14, 2011 at 08:03
This blog was very informative and knowledgeable. Well this is very interesting indeed.Would love to read a little more of this. Great post. Thanks for sharing with us.