0

So I have a section of code for a program I working on that reads in other text files that are specified inside of the first file. However, I am having some problems with my variable, newText and txt. If I use the javascript alert, it will work, but if I take out the alert(txt); my code breaks, and newText is undefined.

function createStates(textArr, numStates, acts)
{
    textArr.splice();
    var states = [];
    var path = window.prompt("Please enter the path to your state files", "");
    for( var i =0; i < numStates; i++)
    {
        // reward for being in state, terminal, then statefile

        var reward = parseInt(textArr.shift());
        var terminal = parseInt(textArr.shift());
        if(terminal == 0)
        {
            var newText = [];
            var nextFile = path + String(textArr[0]);
            var xmlhttp = new XMLHttpRequest();
            var txt;
            xmlhttp.onreadystatechange = function(){
                if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
                    txt = xmlhttp.responseText;
                    newText = String(txt).split(/[\r\n]+/g);
                }
            };;
            xmlhttp.open("GET","file:///" + nextFile,true);
            xmlhttp.send();
            alert(txt);
            var state = new State(reward, acts, newText);
            states.push(state);

        }
        textArr.shift();
    }
    return states;
}

Alse, here is what one of the text files that it is handling looks like,

4 11
0 0 0 0 0 0 0.8 0 0 0.1 0.1
0 0 0 0 0 0 0.1 0 0 0.8 0.1
0 0 0 0 0 0 0 0 0 0.1 0.9
0 0 0 0 0 0 0.1 0 0 0 0.9

And this is for a school project, and I have to read in the files from a local computer. I am using firefox to run this since chrome blocks the loading of local files.

  • 1
    `newText` is set when the AJAX request is completed. Without the alert, you aren't waiting enough time for it to be completed. Look up how asynchronous functions work in JavaScript. – Madara's Ghost Nov 23 '15 at 02:10

1 Answers1

0

Following code will return true if variable is not defined in global scope

window.txt === undefined
Maksym Kozlenko
  • 10,273
  • 2
  • 66
  • 55