详解undefined和null

编程入门 行业动态 更新时间:2024-10-02 16:24:58

<a href=https://www.elefans.com/category/jswz/34/1770044.html style=详解undefined和null"/>

详解undefined和null

详解undefinednull

  1. 出现undefined的几种场景
    // 1. 定义了但没有赋值
    let a;
    console.log(a);  // undefined// 2. 定义了但赋了一个空值
    let obj = {}
    console.log(obj.name); // undefined// 3. 定义了一个函数但是没有返回值
    function Fn() {}
    console.log(Fn());  // undefined// 4. 定义了一个函数,但是调用的时候只传递了第一个参数
    function Fn2(p1,p2) {console.log(p2);
    }
    Fn2(1)   // undefined
    
  2. null出现的场景几种场景
    let obj2 = null;  //设置为null,是为了在以后的某个场景下进行再赋值
    function  Fn3() {return {}
    }
    obj2 = Fn3()  // 2. 获取一个不存在的值
    document.querySelector('#id')  //null// 3.正则表达式
    'test'.match(/a/)  // null
    
  3. undefinednull相同点和不同点
  • 相同点:
    1. 一个对象字面量值 小写的undefinednull

    2. undefinednull的布尔类型都是false 所以undefined!null = true 他们两个就无法通过!判断区分undefinednull

    3. 前端常见的undefinednull的异常

      Uncaught TypeError: Cannot read properties of undefined (reading 'name')
      at <anonymous>:1:15
      
      Uncaught TypeError: Cannot read properties of null (reading 'age')
      at <anonymous>:1:15
      
    4. 在非严格模式的比较下 undefiendnull是相等的

       console.log(undefined == null);  // trueconsole.log(undefined === null);  // false
      

  • 不同点:
    1. nulljavascript的关键字

      • undefinedjavascript的一个全局变量 在浏览器下是挂载在window对象下的
      • console.log(window.undefined); // undefined
    2. 类型不同 undefined的数据类型是undefined null的数据类型是object

    3. call函数调用toString函数时

      Object.prototype.toString.call(null) // [object Null] 
      Object.prototype.toString.call(undefined) // [object Undefined]
      
    4. 字符串类型转换 转换成本身字符串的转换形式

      console.log(null + 'string');   //'nullstring'
      console.log(undefined + 'string');   //'undefinedstring'
      
    5. 参与运算的时候,null会转换为0来运算,undefined会转换成NaN来运算

      console.log(null + 1)  // 1
      console.log(undefined + 1) //NaN
      
    6. 无论什么情况下,没有必要将一个变量显示为undefined,如果需要将某个变量将来用来保存某个数值,将其赋值为null

更多推荐

详解undefined和null

本文发布于:2024-02-27 22:03:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1766278.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:详解   undefined   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!