美文网首页
Javascript 中 undefined 与 null 有啥

Javascript 中 undefined 与 null 有啥

作者: 酷酷的凯先生 | 来源:发表于2020-08-12 10:22 被阅读0次

    先简单说下 undefinednull 是什么东东:

    null: 表示空值,即没有对象被呈现,使用 typeof 运算得到 “object”

    1. 作为函数的参数,表示该函数的参数不是对象。
    2. 作为对象原型链的终点。
    if (typeof(obj) == "object") {
        ... 你想要做的事
    }
    

    undefined: 表示缺少值,此处应该有值,但未定义,使用 typeof 运算得到 “undefined”

    1. 变量被声明了,但没有值时
    2. 调用函数时,应该提供的参数没有提供时
    3. 对象没有赋值的属性,此属性值为 undefined
    4. 函数没有返回值,默认返回undefined
    if (typeof(obj) == "undefined") {
        ... 你想要做的事
    }
    

    typeof 函数返回的是字符串,包括:number、string、boolean、object、function、undefined

    其实 undefinednull 基本是同义的,只有一些细微的差别, 具体如下

    1. 值相等而类型不相等
    var a;
    var b = null;
    console.log(a == b); //ture
    console.log(a ===b); //false
    

    在上面的代码中 == 会进行隐式的类型转换,且值是相等的,即 ture;
    而在=== 中则不会发生类型转换,即 false。
    因此 undefinednull 的值相等而类型不相等。

    1. 数字运算不相同
    1+null  //1
    1+undefined //NaN
    

    这是由于约定的不同所决定的。
    规定中数字与 undefined 运算时,结果都 NaN 。在与 null 运算时,null 始终为0

    1. 具体作法不一样
    想要判断一个值是否存在时
    obj.value === undefined 
    
    想要判断一个对象是否为空时
    obj.value == null 
    

    也可以参照 MDN 上 , 希望对大家有所帮助

    typeof null        // object (因为一些以前的原因而不是'null')
    typeof undefined   // undefined
    null === undefined // false
    null  == undefined // true
    null === null // true
    null == null // true
    !null //true
    isNaN(1 + null) // false
    isNaN(1 + undefined) // true
    

    相关文章

      网友评论

          本文标题:Javascript 中 undefined 与 null 有啥

          本文链接:https://www.haomeiwen.com/subject/dfkpdktx.html