Search code examples
actionscript-3flashactionscriptjquery-animateadobe

indexOf not finding the variable on the array in actionscript 3


This script loads the data flawlessly from the text file to the myArrayofLines

function onLoaded(e:Event):void {
    var myArrayOfLines:Array = e.target.data.split(/\n/);
    for(var t:Object in myArrayOfLines)
  trace(t + " : " + myArrayOfLines[t]);

    trace(myArrayOfLines.indexOf("ace"));

    trace(myArrayOfLines[2]);
       }

Tracing myArrayOfLines[2] correctly displays "ace"

But using indexOf("ace") gives -1 , when it should be displaying 2

Help?

Here is code by Organis , but indexOf still giving -1

var aLoader:URLLoader = new URLLoader;

aLoader.addEventListener(Event.COMPLETE, onLoaded);
aLoader.load(new URLRequest("3letterwords.txt"));

function onLoaded(e:Event):void
{
    var aLines:Array = e.target.data.split(/\n/);

    for (var i:int = 0; i < aLines.length; i++)
    {
        trace(i + " : " + aLines[i]);
    }

   trace(aLines.indexOf("ace"));

    trace(aLines[2]);
       }

Solution

  • Because loading data is an asynchronous operation thus onLoaded event handler is executed after your if block. Basically, the execution order is following:

    // 1
    var myTextLoader:URLLoader = new URLLoader();
    
    // 2
    myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
    
    function onLoaded(e:Event):void
    {
        // 5
        var myArrayOfLines:Array = e.target.data.split(/\n/);
        for(var t:Object in myArrayOfLines)
        trace(t + " : " + myArrayOfLines[t]);
    }
    
    // 3
    myTextLoader.load(new URLRequest("3letterwords.txt"));
    
    // 4
    if ( myArrayOfLines.indexOf( word ) > -1 )
    {
        // Success{
    
        clabelword.text = String(word) + String("good");    
    
    }
    

    That's why at point 4 the script does not have the data... yet.

    The only reliable way to check the loaded data is to put the if block into the event handler or into any code that is executed after the event handler.

    var aLoader:URLLoader = new URLLoader;
    
    aLoader.addEventListener(Event.COMPLETE, onLoaded);
    aLoader.load(new URLRequest("3letterwords.txt"));
    
    function onLoaded(e:Event):void
    {
        var aLines:Array = e.target.data.split(/[\r\t\s]*\n[\r\t\s\n]*/);
    
        for (var i:int = 0; i < aLines.length; i++)
        {
            trace(i + " : <" + aLines[i] + ">");
        }
    
        if (aLines.indexOf(word) > -1)
        {
            clabelword.text = word + "good";
        }
    }