10
Considering the following code:
var a = {};
if (a.b.c !== undefined) {
console.log("definido!");
} else {
console.log("indefinido!");
}
Is there any way to check each property without having to test one by one?
What I want is the result of a if
similar to the following, but simplified:
var a = {};
if (a !== undefined && a.b !== undefined && a.b.c !== undefined) {
console.log("definido!");
} else {
console.log("indefinido!");
}
Problem of the second approach is that if the value of
a
,a.b
ora.b.c
forfalse
, 0 or empty string the output will be undefined– Jéf Bueno
@jbueno is true, I made the reservation
– Maniero
bigown and @jbueno I know it runs a little bit from the question, but you think that thus it gets really bad?
– Sorack
@Sorack can’t tell if it’s abuse of
Object.prototype
because I have little experience with JS, I don’t think so. It seems to me that in this case could eliminate the exception capture and verify each property and is undefined. Not that I’m wrong, but I hate to use exception to solve problems that can be solved with a better mechanism. I don’t like the syntax. I would encapsulate one of the two solutions I passed you in a simple function (the first works in all cases)– Maniero
@bigown got it, I made a change to not need to avail myself of the exception. Value anyway, in case you’re curious thus. I used recursion to get the result
– Sorack