3

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!

8
  • What are x and y? How are they created and modified? Commented Apr 23, 2016 at 22:53
  • It's up to you to make sure that x-1 and y can only be numbers from 0-9. Commented Apr 23, 2016 at 22:57
  • In what scopes do you create and use your array? Because with var it won't be global. Commented Apr 23, 2016 at 22:57
  • How do I make it global then? Commented Apr 23, 2016 at 23:01
  • remove var keyword before variable name Commented Apr 23, 2016 at 23:01

1 Answer 1

2

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};
    })
});
Sign up to request clarification or add additional context in comments.

2 Comments

Please don't recommend such an horrible practice. Declare it with var but in global scope. Or better, wrap all code inside an IIFE.
I've suggested fix and explained the reason why it is not working. Also I've said that it's better to avoid global variables if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.