Goblaz
Goblaz

Reputation: 63

JavaScript 2d array causing "Cannot read property 'undefined' of undefined"

i'm attempting to read from a global 2d array in javascript and it gives me "Cannot read property 'undefined' of undefined".

Here's how I'm defining my array:

var cell = {visited:false, left:true, top:true, right:true, bottom:true}

var cells = new Array(10);

for (i = 0; i < 10; i++) //Initiate 2d cells array.
{
  cells[i] = new Array(cell,cell,cell,cell,cell,cell,cell,cell,cell,cell);
}

I'm then accessing it later like this:

if(x != 0) //Left
{
    if(cells[x-1][y].visited == false)
    {
        //Do something
    }
}

x and y are never out of bounds of the defined array so I'm not sure why this is occuring.

Thanks!

Upvotes: 3

Views: 2174

Answers (1)

Yuriy Yakym
Yuriy Yakym

Reputation: 3911

To create global variable you need create it in global scope or just omit var keyword when declaring it. As I see, you used var keyword, so your variable could be global only if it's created in global scope.

Just use cells = new Array(10); instead of var cells = new Array(10);.

Btw. It is better to avoid global variables if it is possible.

Suggestion

Additionally I'd like to suggest you creating your two-dimensional array this way. You pass your cell variable by reference. So changing it in one place will change it everywhere.

cells = new Array(10).fill().map(function(cell) {
    return new Array(10).fill().map(function() {
        return {visited:false, left:true, top:true, right:true, bottom:true};
    })
});

Upvotes: 2

Related Questions