简体   繁体   中英

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!

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};
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM