简体   繁体   English

我应该在Javascript类型中使用typeof相等吗?

[英]Should I use typeof in Javascript type equality?

What is better? 什么是更好的?

if (obj === undefined) { }

vs.

if (typeof(obj) === 'undefined') { }

If you somehow can't refrain from shadowing the global undefined , or can't keep from trying to reference undeclared variables, then use: 如果你以某种方式不能避免阴影全局undefined ,或者不能试图引用未声明的变量,那么使用:

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;

...where void always returns undefined , and doesn't rely on the global property. ...其中void总是返回undefined ,并且不依赖于全局属性。

Another safeguard you can use is to use shadowing in a good way by defining a proper undefined in a function: 您可以使用的另一个安全措施是通过在函数中定义正确的undefined来以良好的方式使用阴影:

(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 ) {

    }

})();

I would go with the second one, as "undefined" is not a reserved word. 我会选择第二个,因为“未定义”不是保留字。 Example: 例:

var obj = undefined;
undefined = {};

if(obj === undefined) {
    console.log("undefined 1");   
}

if(typeof obj === 'undefined') {
    console.log("undefined 2");   
}

Will only show "undefined 2" because the variable undefined can be changed. 只显示“undefined 2”,因为可以更改undefined变量。

This has been asked before, but the more common approach is to do this: 之前已经问过这个问题,但更常见的方法是这样做:

     typeof(x) == 'undefined'

See: JavaScript: undefined !== undefined? 请参阅: JavaScript:undefined!== undefined?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM