什么更好?
if (obj === undefined) { }
对比
if (typeof(obj) === 'undefined') { }
最佳答案
如果你无法避免隐藏全局undefined
,或者无法避免引用未声明的变量,那么使用:
typeof x === 'undefined'
如果您坚持良好的编码习惯,并相信让损坏的代码崩溃,请使用:
x === undefined
如果你想要不同的选择,你可以使用:
x === void 0;
...其中 void
始终返回 undefined
,并且不依赖于全局属性。
您可以使用的另一个保护措施是通过在函数中定义适当的 undefined
以良好的方式使用阴影:
(function( undefined ) {
// notice that no arguments were passed,
// so the `undefined` parameter will be `undefined`
var x;
if( x === undefined ) {
}
})();
...有些人喜欢给它一个不同的名字:
(function( undef ) {
// notice that no arguments were passed,
// so the `undefined` parameter will be `undefined`
var x;
if( x === undef ) {
}
})();
关于javascript - 我应该在 Javascript 类型相等中使用 typeof 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6481802/