2 Replies Latest reply on Dec 8, 2007 11:52 AM by Greg Dove

    for( ... in) over Array error

      I have a loop over an array that breaks in one instance... as far as I can tell. I'm a little concerned because I use the same code in many locations... and the bug is not always easy to pinpoint. The array is composed of references to a class that extends MovieClip. Here's the code that broke:

      for(var i:String in Child_arr){
      Child_arr .DoSomething()
      Only the last element in the array was being called. After narrowing down the error to this loop, scratching my head, I rewrote the line as:

      for(var i = 0; i < Child_arr.length; i++){
      This worked. Again, the problem is I use the 1st syntax all over the place... and it works - I think. There may be some other, one off random place the error happens, and it'll byte me again.

      the i var is not being changed, the array is not modified.

      Any clues????

        • 1. Re: for( ... in) over Array error
          Greg Dove Level 4
          With arrays, I think its better to do the numeric iteration over the array indices rather than over the properties. If an array is extended (or the the array prototype) without setting the actionscript prop flags to hide the new properties you could have unexpected results.

          simple example:
          var xx:Array = new Array(1,2,3,4,5);
          xx.oops= function(){};
          for (var i in xx) {
          trace(xx[ i ])

          Also the for.. in loop seems to work from the most recently added item backwards... like going from the top of a stack. So it would not be unusual for it to start with the last item with this type of loop.

          Beyond that ,if you really want to fix this.. then see what you get with the trace output, if the DoSomething method returns something, check that too. Perhaps doing your somethings in the wrong order is not good?

          for(var i:String in Child_arr){
          trace('requesting '+Child_arr[ i ]);
          trace(Child_arr[ i ].DoSomething());
          • 2. Re: for( ... in) over Array error
            Greg Dove Level 4
            Hmm. I just tried that and it seemed to iterate in the correct order with my test. Perhaps that's not it after all. It's strange because I'm pretty sure I've observed the reverse iteration order before with for..in .