JSFL for...in loop doesn't seem to work
I'm writing a script in JSFL for Flash CS5, and I'm trying to get a list of layers off the main timeline. I'm getting the timeline, then looping through it all with a for...in loop, but the objects I'm getting seem to be undefined. Here's some test code I made:
alert(fl.getDocumentDOM().getTimeline().layers[0].name); //Returns "text1"
for(layer in fl.getDocumentDOM().getTimeline().layers) {
alert(layer.name); //Returns "undefined"
}
So, does JSFL not support for...in? That's kinda odd, since it seems it's just a Jav开发者_如何转开发aScript engine.
Whoooh there. JSFL is not just a JavaScript engine, it is bizarro world JavaScript which can be remarkably unpredictable. Don't believe me? Not sure if this is still the case, but try fl.getDocumentDOM().selection.push(<obj>)
. It didn't work, but this did: var s = fl.getDocumentDOM().selection; s.push(<obj>) fl.getDocumentDOM().selection = s
.
That said, your syntax is off:
var layers = fl.getDocumentDOM().getTimeline().layers;
// include 'var' it's good taste
for(var layer in layers) {
// for... in iterates the KEYS, so you actually have to do a lookup
alert(layers[layer].name);
}
As an aside, you're better off iterating through arrays with numeric indexes, it is clearer and faster.
You should never loop over an Array using for..in, as it's designed for Object enumeration. All it takes is for another script to modify the Array.prototype and your for..in breaks (if you don't believe me, extend the Object.prototype and watch the Adobe IK Tool start spitting out errors!)
The cleanest way to loop over Arrays in JSFL (which uses the Spidermonkey JavaScript engine) is:
for each(var layer in layers)
{
fl.trace(layer.name);
}
PS. @cwallenpole. The selection modification "unpredictability" you speak of is normal behaviour: http://help.adobe.com/en_US/flash/cs/extend/WS5b3ccc516d4fbf351e63e3d118a9024f3f-7f91.html
精彩评论