zoukankan      html  css  js  c++  java
  • JavaScript中Null和undefind区别

    公众号原文

    Javascript有5种基本类型:Boolean,Number,Null,Undefined,String;和一种复杂类型:Object(对象);

    undefined:只有一个值,及特殊的undefined。在使用var声明变量但未对其初始化时,这个变量的值是undefined,简言之,undefined就是表示变量申明了但未初始化时的值。

    注意:尚未声明的值直接alert其值会报错而不是显示undefined;但是如果一个申明了未赋值的变量与未声明的变量所显示的typeof结果是一样的--->undefined

    代码示例:

    <script type="text/javascript">
    
    var str;
    
    alert(typeof str);//undefined
    
    alert(typeof message);//undefined
    
    </script>

    undefined在参与数值运算时一定是NAN,在与字符串拼接相加时则直接显示undefined;

    代码示例:

    <script type="text/javascript">
    
    var b;
    
    alert(b+3);//输出 NAN
    
    alert(b+'3');//输出 undefined3
    
    </script>

    null:示准备用来保存对象,还没有真正保存对象的值。从逻辑角度看,null值表示一个空对象指针。也就是说 null是相对于对象而言的,所以typeof(null) 为object。

    null在参与数值计算时其值自动转换为0,而进行字符串相加拼接时会以字符串“null”的方式显示

    代码示例:

    <script type="text/javascript">
    
    var a=null;
    
    alert(null+3+5);//8
    
    alert(null+'hellow');//nullhellow
    
    alert(null+3+'hellow');//3hellow
    
    alert(null+'hellow'+3);//nullhellow3
    
    </script>
    

      

    联系:alert(null=undefined);//true   ECMAScript认为undefined是由null派生出来的,所以将他们定义为相等。

    如何区分?

    alert(typeof null == typeof undefined);
    
    alert(null === undefined);

     

  • 相关阅读:
    java_web连接SQL_server详细步骤
    探索需求-设计前的质量之二
    EF三种编程方式详细图文教程(C#+EF)之Code First
    EF三种编程方式详细图文教程(C#+EF)之Model First
    EF三种编程方式详细图文教程(C#+EF)之Database First
    探索需求-设计前的质量之一
    编写有效用例之三
    编写有效用例之二
    golang 环境安装
    golang 命令详解
  • 原文地址:https://www.cnblogs.com/hgmyz/p/7409870.html
Copyright © 2011-2022 走看看