Question

I have the JS below.

  • An array of objects. Each object with an "s" and "e" property.
  • The first for loop is a test to log the "s" and "e" properties for the first item on the array.
  • The second loop is where I want the working code to happen, but I can't get access to my properties from inside this loop. And this only seems to be happening in IE8 and lower.

The error in IE8 I'm getting is:

's' is null or not an object

Any ideas would be appreciated?

var t = [
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
];

var obj = t[0];
for (var prop in obj) {
    console.log(prop+": "+obj[prop]);
}

for (var i = t.length - 1; i >= 0; i--) {
    var l = t[i];
    var s = l.s;
    console.log(s);
}
Was it helpful?

Solution

You have a comma after the last object in your t array. Remove it, because it is getting an undefined as your first object in the loop, because in IE8 it would not initially throw an error but it would acquire an empty object. This is the reason why you get the error.

Your code:

var t = [
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    undefined // How IE8 parses it and your loop starts here
];

This wouldn't throw errors:

var t = [
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"} // No comma so array is terminated here
];

OTHER TIPS

the last element in array is null. try remove the last "," in the array

var t = [
{s: "blah", e: "blah blah"},
{s: "blah", e: "blah blah"},
{s: "blah", e: "blah blah"},
{s: "blah", e: "blah blah"}
];

Common mistake:

var t = [
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},  // remove the comma
];

var t = [
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"},
    {s: "blah", e: "blah blah"}  
];

now will works fine in IE8... I tested it: http://jsfiddle.net/SnakeEyes/qFgjh/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top