我应该在Javascript类型中使用typeof相等吗? [英] Should I use typeof in Javascript type equality?
问题描述
什么更好?
if (obj === undefined) { }
vs。
if (typeof(obj) === 'undefined') { }
推荐答案
如果你以某种方式不能避免阴影全局 undefined
,或者不能试图引用未声明的变量,那么使用:
If you somehow can't refrain from shadowing the global undefined
, or can't keep from trying to reference undeclared variables, then use:
typeof x === 'undefined'
如果你坚持良好的编码习惯,并且相信让破解的代码破解,请使用:
If you adhere to good coding practices, and believe in letting broken code break, use:
x === undefined
如果您想要其他替代方案,可以使用:
If you want a different alternative, you can use:
x === void 0;
...其中 void
总是返回 undefined
,并且不依赖于全局属性。
...where void
always returns undefined
, and doesn't rely on the global property.
您可以使用的另一个安全措施是在阴影中使用阴影通过在函数中定义正确的 undefined
的好方法:
Another safeguard you can use is to use shadowing in a good way by defining a proper undefined
in a function:
(function( undefined ) {
// notice that no arguments were passed,
// so the `undefined` parameter will be `undefined`
var x;
if( x === undefined ) {
}
})();
...有些人更喜欢给它一个不同的名字:
...some people prefer to give it a different name:
(function( undef ) {
// notice that no arguments were passed,
// so the `undefined` parameter will be `undefined`
var x;
if( x === undef ) {
}
})();
这篇关于我应该在Javascript类型中使用typeof相等吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!