Stefan Delport Stefan Delport - 5 months ago 8
Javascript Question

Error: Is null or not an object

I've used a multidimensional array in javascript to store data which I use to generate content dynamically, and it works fine in any webkit browser as well as firefox and IE 9 and up but for some reason IE 8 (where i tested it) and IE 7 (which I emulated) gives me an error "is null or not an object" on the following code:

var data =
[
["A","X",[5,6],3,2014],
["V","L",[9,10],4,2014],
["X","N",[10,11],6,2014]
];
for(var t=0;t<data.length;t++){
if(data[t][3]==i){
alert("Found");
}
}


The error specifically says '3' is null or not an object and refers to the 3 in the if statement. Could the error be because i don't declare the array as

var data=new Array();


or is there another problem?

additional Info: This code is in a document ready event for jQuery.

Answer

The code in the question doesn't produce that error, but if you have a trailing comma after the last item in the array, it will:

var data =
    [
    ["A","X",[5,6],3,2014],
    ["V","L",[9,10],4,2014],
    ["X","N",[10,11],6,2014],
    ];
for(var t=0;t<data.length;t++){
  if(data[t][3]==i){
     alert("Found");
   }
}

In IE8 and earlier, that array will have four items instead of three, and the last item will be undefined. When t is 3, data[t] will return undefined, and applying the [3] to that will case that error message. It says that " '3' is null or not an object" because 3 is the index that you used to get the value that isn't an object.