• Javascript中Null和Undefined的区别[转]


    在JavaScript中存在这样两种原始类型:Null与Undefined。这两种类型常常会使JavaScript的开发人员产生疑惑,在什么时候是Null,什么时候又是Undefined?

    Undefined类型只有一个值,即undefined。当声明的变量还未被初始化时,变量的默认值为undefined。
    Null类型也只有一个值,即null。null用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象。

     
    1. var oValue;  
    2. alert(oValue == undefined); //output "true"  


    这段代码显示为true,代表oVlaue的值即为undefined,因为我们没有初始化它。

     
    1. null == document.getElementById('notExistElement'));  


    当页面上不存在id为"notExistElement"的DOM节点时,这段代码显示为"true",因为我们尝试获取一个不存在的对象。

     
    1. typeof undefined); //output "undefined"  
    2. alert(typeof null); //output "object"  


    第一行代码很容易理解,undefined的类型为Undefined;第二行代码却让人疑惑,为什么null的类型又是Object了呢?其实这是JavaScript最初实现的一个错误,后来被ECMAScript沿用下来。在今天我们可以解释为,null即是一个不存在的对象的占位符,但是在实际编码时还是要注意这一特性。

     
    1. null == undefined); //output "true"  


    ECMAScript认为undefined是从null派生出来的,所以把它们定义为相等的。但是,如果在一些情况下,我们一定要区分这两个值,那应该怎么办呢?可以使用下面的两种方法。

     
    1. null === undefined); //output "false"  
    2. alert(typeof null == typeof undefined); //output "false"  


    使用typeof方法在前面已经讲过,null与undefined的类型是不一样的,所以输出"false"。而===代表绝对等于,在这里null === undefined输出false。

    ========================================================================================

    在javascript中什么情况出现下面三种情况: null undefined “ ” 
    文件1:null_undefined.html 
    文件2:null_undefined.js 

    null_undefined.html 
    【见文章评论一】 
    null_undefined.js 
    var test = function() 

    alert(window.aiter2008); //弹出undefined window空间中没有aiter2008这个变量 
    alert(document.getElementById("test_text1111")); //null 在上面的null_undefined.html文件中没有test_text1111元素 
    var testText = document.getElementById("test_text").value; // test_text输入框中没有输入任何元素 
    alert(testText==""); //true 
    alert(testText==null); //false 

    这次测试可以得到结论: 
    一个对象中没有指定的变量,而要使用,会出现 undefined 
    Html中没有的元素,通过document.getElementById("")查找的结果为: null 
    Html中有的元素,但是没有任何值,通过document.getElementById("")查找的结果为:” ”; 不是null 
    2 null_undefined.html文件不变 
    null_undefined.js 
    var test = function() 

    var testText = document.getElementById("test_text"); 
    var testName = testText.name; 
    var testUn = testText.name11; 
    alert("test_text's name::"+testName); // test_text's name:: test_text 
    alert("test_text's name11:::"+testUn); // test_text's name11:::undefined 

    结论 
    一个对象没有的属性,调用会出现: undefied 这和调用window的aiter2008属性一样

     

    本文来自: 脚本之家(www.jb51.net) 详细出处参考:http://www.jb51.net/article/13202_2.htm

  • 相关阅读:
    Atom+latex+中文环境
    pytorch中,不同的kernel对不同的feature map进行卷积之后输出某一个channel对应的多个feature map如何得到一个channel的feature map
    Ubuntu16.04上添加用户以及修改用户所属的组
    shell批处理文件,并将运算结果返回
    pytorch如何能够保证模型的可重复性
    Linux用管道命令对文件的移动
    python中调用多线程加速处理文件
    Python中random模块在主函数中设置随机种子是否对于调用的函数中的随机值产生影响?
    pytorch统计模型参数量
    pytorch使用tensorboardX进行网络可视化
  • 原文地址:https://www.cnblogs.com/kkwoo/p/3557602.html
Copyright © 2020-2023  润新知