Pergunta

I'm iterating through an array of simple (JSON-style) objects, some of which have a given property, and some that don't. If they have that property, it's safe to assume that it will never evaluate to a falsy value.

var objs = [
    {'a': 1, 'b': 2, 'c': 3},
    {'a': 4, 'b': 5},
    {'a': 7, 'b': 8, 'c': 9}
];

My rather large application is triggering some (very unhelpful) errors in Internet Explorer 8, so I just want to cross this off the list of potential issues. Is it safe to use:

for (var i = 0; i < objs.length; ++i) {
    if (objs[i].c) {
        // objs[i].c is defined
    }
}

I've used this sort of check many times in the application code, but do I need to be using obj.hasOwnProperty('c') or typeof obj.c != 'undefined'?

Thanks.

Foi útil?

Solução

... it's safe to assume that it will never evaluate to a falsy value.

No, it's not safe. If you'd have an object like {'a': 1, 'b': 2, 'c': 0}, objs[i].c will be evaluated falsy. (Or c equals to false, NaN, null, undefined or ''.)

If you want just to know, if there's a property defined in an object, you can do 'c' in objs[i], but beware, this will also include properties from the prototype chain.

If you want to avoid getting properties from the prototype chain, hasOwnProperty check needs to be done.

There's also Object.keys available in modern browsers, though it's not handy on quick-checks.

Outras dicas

I think below one is good to check that particular object has a property. I also used this method on web application frequently.

 obj.hasOwnProperty('c') 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top