在Javascript中,我经常会遇到这样的问题。假设我有一个像这样的对象:
var acquaintances = {
types: {
friends: {
billy: 6,
jascinta: 44,
john: 91
others: ["Matt", "Phil", "Jenny", "Anna"]
},
coworkers: {
matt: 1
}
}
}
在我的理论程序中,我唯一确定的是
acquaintances
是一个对象;我不知道是否已经设置了acquaintances.types
或者其中是否设置了friends
。
我该如何高效地检查acquaintances.types.friends.others
是否存在?
通常我会这样做:
if(acquaintances.types){
if(aquaintances.types.friends){
if(acquaintances.types.friends.others){
// do stuff with the "others" array here
}
}
}
除了繁琐之外,这些嵌套的if语句在实践中管理起来有点难以应对(我的对象比这个例子更复杂!)。但是如果我直接尝试类似于
if(acquaintances.types.friends.others){)
,并且types
还没有被设置,那么程序将会崩溃。Javascript有哪些整洁、可管理的方法来解决这个问题?
?
运算符,符合您的描述,请参见此处。不知道在普通JS中是否有简单的技巧。 - Jokester