zoukankan      html  css  js  c++  java
  • JavaScript null和 undefined 的区别是什么?

    面试被问到,不是很会,学习下。

    区别

    null 表示没有对象(空对象指针),转化为数值时为 0 ,这也是为什么 typeof null 返回 object 的原因。

    console.log(Number(null)) // 0
    console.log(typeof null) // object
    

    undefined 表示缺少值,转化为数值时为 NaN

    console.log(Number(undefined)) // NaN
    

    undefined 典型用法

    1. 变量被声明了,但没有赋值时,就等于 undefined 。
    let num
    console.log(num) // undefined
    
    1. 调用函数时,应该提供的参数没有提供,该参数等于 undefined。
    function fun(a) {
      console.log(a) // undefined
    }
    fun()
    
    1. 对象没有赋值的属性,该属性的值为 undefined。
    const obj = {}
    console.log(obj.a) // undefined
    
    1. 函数没有返回值时,默认返回 undefined 。
    function fun() {}
    console.log(fun()) // undefined
    

    null 的典型用法 :

    1. 作为函数的参数,表示该函数的参数不是对象,用于判断。
    function fun(a) {
      if (a !== null) {
        // 进行一系列操作
      }
    }
    
    1. 作为对象原型链的终点。
    console.log(Object.prototype.__proto__) // null
    
  • 相关阅读:
    Version
    Windows Server Protocols (WSPP)
    Tomcat启动问题jvm访问拒绝的解决方法
    vue3中使用draggable插件实现元素的拖拽,排序,克隆
    消息队列的思考
    jenkins_ssh
    jenkins_构建配置
    minikube清理sh
    stream源码导读
    源码rabbit_3_消息链路追踪
  • 原文地址:https://www.cnblogs.com/cqkjxxxx/p/14975545.html
Copyright © 2011-2022 走看看