Home  >  Q&A  >  body text

javascript - a === undefined和typeof a === 'undefined'哪个好?

记得之前看过一个javascript编程风格指南(好像是腾讯的一个团队的),里面说typeof a === 'undefined'要比用a === undefined要好,是不是这样的?如果是的话,为什么?

巴扎黑巴扎黑2748 days ago1470

reply all(4)I'll reply

  • 迷茫

    迷茫2017-04-11 12:32:50

    常见的有三种比较 undefined 的方法,看代码

    var test1 = (function(undefined) {
        return function() {
            var value;  // undefined
            console.log("test1", value === undefined);
        };
    })("hello");
    
    var test2 = (function(undefined) {
        return function() {
            var value;  // undefined
            console.log("test2", typeof (value) === "undefined");
        };
    })("hello");
    
    var test3 = (function(undefined) {
        return function() {
            var value;  // undefined
            console.log("test3", value === void (0));
        };
    })("hello");
    
    test1();
    test2();
    test3();

    由于 javascript 的 undefined 是可以重定义的,所以上面的代码模拟了 undefined 被重新定义了的情况,结果可以看到 value === undefined 判断出错了。另外两种办法,其实差不多,不过明显 value === void(0) 写的字要少些,懒人可选!

    注:上面的代码都是在 value 变量被定义了的情况。如果连变量都没定义,只有 typeof(value) 不会抛异常出来。

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-11 12:32:50

    是这样的 ,因为如果您a变量未初始化时的话用 a=== undefined会直接抛异常导致js代码终止,用typeof就不会

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-11 12:32:50

    不过你a变量未初始化未声明时,用 typeof a一样显示'undefined',和var a; 后的typeof a 结果一样,这个也要考虑到

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-11 12:32:50

    function test1() {
      console.log(typeof aaa === 'undefined');
    }
    
    function test2() {
      console.log(aaa === undefined);
    }
    
    test1(); // true
    test2(); // 报错,Uncaught ReferenceError: aaa is not defined

    javascript 中为什么要用typeof x === 'undefined'

    reply
    0
  • Cancelreply