views:

23

answers:

1

I have to assume I am missing something simple, or I am not understanding something, but I can't seem to figure this.

I have a list of strings that I add to an array, then attempt to set those values in a for-loop using data that I read in. The array gets updated, but the values the array contains do not. I also have an array of buttons that I update this same way that works great, but strings don't seem to work the same way. I have tried moving the string array to give it full scope, and still nothing... What am I missing?

public class test extends Sprite
{
  // Declare a list of strings 
  protected var title0:String = undefined;
  protected var title1:String = undefined;
  protected var title2:String = undefined;

  protected function onDataLoad(evt:Event):void{

    var titleArray:Array = new Array(title0,title1,title2); // Array of strings

    for(i=0; i<=evt.target.data.count; i++){
      titleArray[i] = evt.target.data["title"+i]; // attempt to set the title values
    }
  }

  protected function function0(e:Event):void {
    trace("My title is: " + title0); // title0 is null
  }
}
A: 

It has to do with how AS3 stores Array elements. You would need to explicitly set both the instance property (title1, title2, title3) and the associated array element (array[0], array[1], array[2]) to achieve what you want. Or, you could drop the instance properties (title0, title1, title2) completely and just use the array to store your values. Something like:

public class test extends Sprite
{

  protected var _titleArray:Array = [];

  protected function onDataLoad(evt:Event):void{

    for(i=0; i<=evt.target.data.count; i++){
       // set the title values
      _titleArray[i] = evt.target.data["title"+i];
    }
  }

  protected function function0(e:Event):void {
    trace("My title is: " + _titleArray[0]);
  }
}
heavilyinvolved
This is what I should have done to begin with... much more flexible. The only thing I changed was I pushed the title values onto the array rather than set them by index (just a personal preference)._titleArray.push(evt.target.data["title"+i]);
taipan
Yup, that's a cleaner approach for sure. Glad to help!
heavilyinvolved