5.37 isUndefined

5.37.1 语法

_.isUndefined(value)

5.37.2 介绍

如果value是undefined,返回true。

5.37.3 代码示例

示例一:window一个不存在的变量

_.isUndefined(window.missingVariable);  //=> true

示例二:各种

_.isUndefined(1) //=> false
_.isUndefined(null) //=> false
_.isUndefined(false) //=> false
_.isUndefined(NaN) //=> false
_.isUndefined() //=> true
_.isUndefined(undefined) //=> true

5.37.4 自己实现一个isUndefined

function isUndefined(value){
    return value === undefined;
}

isUndefined(window.missingVariable);  //=> true
isUndefined(1);  //=> false;

5.37.5 上面例子的bug请在IE7下看看

function isUndefined(value){
    return value === undefined;
}
undefined = 1; //undefined被改变
alert(isUndefined(1));

5.37.6 其他写法的思考

//typeof
function isUndefined(value){
    return typeof value === 'undefined';
}

//underscore的写法
function isUndefined(value){
    return value === void 0; 
}

//{}的写法,多一个对象,效率上不足
function isUndefined(value){
    return value === {}.a; 
}

5.37.7 undefined的情况

  • 使用了一个并不存在的变量

    typeof aaa;
    
  • 使用了已经声明但还没有赋值的变量

    var aaa;
    
  • 使用了一个并不存在的对象属性时,返回的是undefined

    console.log({}.aaa);