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);

     

  • 相关阅读:
    HTML 样式表
    HTML笔记(框架)
    HTML笔记1
    SQL server 笔记9(备份还原触发器事务三范式)
    拦截器传参问题
    MethodFilterInterceptor(方法拦截器)配置excludeMethors
    js基础学习笔记(五)
    js基础学习笔记(四)
    笔记:CSS常用中文字体英文名称对照表
    推荐:掌握单页网站设计的5大技巧(转)
  • 原文地址:https://www.cnblogs.com/hgmyz/p/7409870.html
Copyright © 2011-2022 走看看