javascript - JSFL for...in loop doesn't seem to work - Stack Overflow

I'm writing a script in JSFL for Flash CS5, and I'm trying to get a list of layers off the ma

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 JavaScript engine.

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 JavaScript engine.

Share Improve this question asked Jul 9, 2011 at 2:50 Alexis KingAlexis King 43.9k16 gold badges142 silver badges215 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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./en_US/flash/cs/extend/WS5b3ccc516d4fbf351e63e3d118a9024f3f-7f91.html

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744750794a4591580.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信