1

I have a simple check to see if a particular set of keys is an array and if not create it but for some reason the if statement returns an error, this is what I am trying to do:

//test data
var i = 0;
var map = new Array(); 
var Data[i]['x'] = 6;
var Data[i]['y'] = 7;

if(!map[Data[i]['x']] instanceof Array){
   map[Data[i]['x']] = new Array();
}

if(!map[Data[i]['x']][Data[i]['y']] instanceof Array){ //error on this line
   map[Data[i]['x']][Data[i]['y']] = new Array();
}

The error is:

Uncaught TypeError: Cannot read property '6' of undefined

This error is occuring on the second IF statement. What is the mistake I am making here?

4
  • 1
    Can you post a demo to jsfiddle? Commented Dec 29, 2012 at 2:45
  • You haven't declared i Commented Dec 29, 2012 at 2:47
  • oops i forgot to paste i into the question :P Commented Dec 29, 2012 at 2:47
  • @MichaelBerkowski jsfiddle.net/bH6aG/1 Commented Dec 29, 2012 at 2:49

1 Answer 1

5

In the first if statement:

if(!map[Data[i]['x']] instanceof Array)

is being parsed as:

if((!map[Data[i]['x']]) instanceof Array)

At that point, map[6] is undefined, so !map[6] is true, and true is not an instance of Array. So it doesn't set it to new Array().

Change it to:

if (!(map[Data[i]['x']] instanceof Array))
Sign up to request clarification or add additional context in comments.

Comments

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.