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

时间:2011-06-26 02:35:47

标签: javascript performance

什么更好?

if (obj === undefined) { }

VS

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

3 个答案:

答案 0 :(得分:4)

如果你以某种方式无法避免阴影全局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 ) {

    }

})();

答案 1 :(得分:1)

我会选择第二个,因为“未定义”不是保留字。例如:

var obj = undefined;
undefined = {};

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

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

仅显示“未定义2”,因为变量undefined可以更改。

答案 2 :(得分:-1)

以前曾经问过,但更常见的做法是:

     typeof(x) == 'undefined'

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

相关问题