开发者

ie gives "...is null or not an object" errors when accessing an object?

开发者 https://www.devze.com 2023-01-31 00:04 出处:网络
I\'ve got a JavaScript object literal: var things = { \"a\": { 7: { \"b\": \"asdf\", \"z\": { 1: { \"name\": \"Ship0\",

I've got a JavaScript object literal:

var things = {
    "a": {
        7: {
            "b": "asdf",
            "z": {
                1: {
                    "name": "Ship0",
                    "loa": 100,
                    "draft": 5000
                },
                2: {
                    "name": "Ship1",
                    "loa": 100,
                    "draft": 5000
                }
            }
        },
        8: {
            "b": "fdsa",
            "z": {
                5: {
                    "name": "Ship0",
                    "loa": 100,
                    "draft": 5000
                },
                6: {
                    "name": "Ship1",
                    "loa": 100,
                    "draft": 5000
                }
            }
       开发者_如何转开发 }
    }
};

... and later in a function, I do this:

function p_get_index_of_existing_ship(customer_id, ship_id)
{
    return someotherfunctionof(ship_id, things["a"][customer_id]["z"]);
}

It works nicely in firefox, but in IE(7,8) I get "error: 'things.a[...].z' is null or not an object.

Is that not the right way to access such associative arrays (objects) in javascript?


The keys of object literals must be valid identifier names. Your keys are 7 and 8 which are not valid names (because the first (and only) character is a digit). I suggest using strings instead:

"7": { ... }

Edit: I looked up the spec... It seems that numeric literals are valid names for keys... but it still could be that IE doesn't like them. Try strings and you'll know.

Edit: Try this:

function p_get_index_of_existing_ship(customer_id, ship_id)
{
    // return someotherfunctionof(ship_id, things["a"][customer_id]["z"]);
    things["a"][customer_id]["z"];
}

Does the error still show in IE?


The problem is ...[customer_id] evaluates to undefined.

Now, figure out why.

0

精彩评论

暂无评论...
验证码 换一张
取 消