0

At the top of my script I define an array as follows: var array = [];

Some nested functions later involving loading of files, the only time I know how many times to iterate, I give it a new dimension like so: array[i] = [];

After jumping from function to function for the sake of how everything is loaded and calculated, I try to access array[i][j] but it tells me that array[i] is undefined.

Here's an example code snippet:

var array1 = [];
var array2 = [];
var array3 = [];
var loader = new THREE.FileLoader();

...

function LoadLevel()
{
    loader.load(
        "level1.lev",
        // onLoad
        function(data)
        {
            var entirelevel = data.split("\r\n");
            var l = "";
            var pos = 0;
            while( l.toLowerCase().trim().indexOf("world things") < 0 && pos < entirelevel.length)
            {
                ...
            }
            numthings = parseInt(l.substring(13));

...

function LoadModels()
{
    curthing=0;
    for(var i=0; i<numthings; i++)
    {
        loader.load(
            array3[i],
            // onLoad
            function(data)
            {
                var entiremodel = data.split("\r\n");
                array1[i] = [];
                var l = "";
                var pos = 0;
                while(...

                if(curthing == numthings)
                    GenerateModel();

...

function GenerateModel()
{
    for(var i=0; i<numthings; i++)
    {
        array2[i] = [];
        for(var j=0; j<numfaces[i]; j++)
        {
            for(var k=0; k<array1[i][j]; k++)...
                   TypeError: array1[i] is undefined
Edward
  • 495
  • 1
  • 6
  • 20
  • Step through the code in your browser or use console.log to monitor what array1 looks like. The error means what it sounds like... you are trying to access an element of array1 you haven't defined yet. – IrkenInvader Feb 03 '18 at 00:38
  • 1
    You are getting this behavior because when `function(data)` (in `LoadModels`) is executed, `i` holds the *current* value of `i`, not the value of `i` when the function was created. – Tibrogargan Feb 03 '18 at 00:43

0 Answers0