我的代码受到以下方面的污染:
if( typeof( objectVar ) === 'object' && objectVar !== 'null' )
if( typeof( objectVar.other ) === 'object' && objectVar.other !== 'null' )
// OK, objectVar.other is an object, yay!
}
}
这有点荒谬。我追求的是这样的功能:
isProperObject( objectVar.other );
考虑到如果未定义
objectVar
,这实际上会失败,也许我应该这样做:isProperObject( 'objectVar.other' );
然后该函数可以
eval()
它。但不是!它无法做到这一点,因为isProperObject()
属于另一个范围,没有objectVar
的范围。因此,可能是:
isProperObject( objectVar, 'other' )
好的,这可以工作。是否有实际上经常使用的这种功能?
最佳答案
您的支票不必要地冗长。您可以改为:
if (objectVar != null && objectVar.other != null) {
// OK, objectVar.other is an object, yay!
}
这将同时检查
null
和undefined
,从而为您提供所需的安全性。或者,如果您确实需要
.other
作为对象:if (objectVar && typeof objectVar.other === "object") {
// OK, objectVar.other is an object, yay!
}
另外,您应该已经测试过:
!== null
代替:
!== 'null'
这是一种不同的新颖方法:
if((objectVar || {}).other != null) {