Search code examples
arraysflashactionscript-3flash-cs5scripting-language

pushing or adding arrays as values into a multi-dimensional array in actionscript 3.0


I am running into some trouble adding an array into another array to create a multi-dimensional array.

The code appears as below:

var slideDataArray:Array = new Array();
var slideShowDataArray:Array = new Array();

slideDataArray[0] = xmlData.SlideShowParameters.SlideShowImagesDirectory;
slideDataArray[1] = xmlData.SlideShowParameters.SlideShowTimeInterval.valueOf();
slideDataArray[2] = xmlData.SlideShowParameters.SlideShowWidth.valueOf();
slideDataArray[3] = xmlData.SlideShowParameters.SlideShowHeight.valueOf();
slideDataArray[4] = slides.length();

slideShowDataArray[0] = slideDataArray;

for (i = 0; i < slides.length(); i++)   {
    // Read data from Slides tag in the XML file into slideDataArray 
    slideDataArray[0] = slides[i].SlideImage.toString();
    slideDataArray[1] = slides[i].SlideText.toString();
    slideDataArray[2] = slides[i].SlideLink.toString();

    // Input the data from slideDataArray into the array for the slideshow (slideShowDataArray) 
    slideShowDataArray[i + 1] = slideDataArray;
}
// end of FOR loop

I am looking for a means of placing the slideDataArray into a 'slot' or value of slideShowDataArray so that I can in the end pass the slideShowDataArray as a parameter to another function.

As of now, the last slideDataArray appears 11 times (the loop runs 11 times) in slideShowDataArray and the way the code is written the slideDataArray is unique every iteration of the loop.

Any help is appreciated.

Thanks in advance...


Solution

  • Remember you are not adding an array, but a reference to slideDataArray to your multidimensional array. Each reference points to the same array - which just contains different values on every iteration of the loop. In other words: Every time you add that reference, you "link" to the same address in memory.

    To get around this, move the inner part of the loop to a separate function and create a new local array on every call:

    function createDataArray ( slide:Object ) : Array {
        var slideDataArray:Array = [];
        slideDataArray[0] = slide.SlideImage.toString();
        slideDataArray[1] = slide.SlideText.toString();
        slideDataArray[2] = slide.SlideLink.toString();
        return slideDataArray;
    }
    

    Then call it from your loop:

    for (i = 0; i < slides.length(); i++)   {
        slideShowDataArray.push( createDataArray (slides[i]) );
    }
    

    You should end up with 11 unique arrays instead of one array that is overwritten 11 times.