浅谈 null & undefined

1.初识 null & undefined

在javascript 中有两种特别的基本数据类型 null undefined 初学者 对其也很模糊或者直接认为它俩相等。

确实在判断 是否为真值时null 和undefined 也就是if语句中 它俩都是为 false, 甚至有javascript

console.log( null == undefined )      // true

2. 深刻理解 undefined & null

在js中咱们常常用一个 typeof来检测一个变量的类型, 并且返回的是一个字符串类型。看下面的例子java

console.log( null === undefined )  // true?  X

答案是否认的. 咱们试着用 typeof 打印一下 null 和undefinedgit

console.log( typeof null)                  // object
console.log( typeof null === "object")      // true
console.log( typeof undefined )              // undefined
console.log( typeof undefined === "undefined" )   // true undefined

咱们发现 null 打印的是 object对象 而 undefined 打印的是undefined. (对于null 打印出object 有兴趣的能够去看看《你不知道的javaScript》中卷 第一章)github

3. 用法

null: 表示 "没有对象", 也就是不该该有值。
  1. 做为函数参数, 表示该函数的参数不是对象
  2. 对象原型链的终点。 也是null .对原型链不熟悉的同窗能够看看.
console.log(Object.prototype.__proto__ === null) // true
undefined: 表示 没有值 缺乏值 就是此处应该有个值可是没有定义
  1. 变量被申明了可是没有被赋值函数

    var a ;
        console.log( a )   // undefined
        a = 2;
        console.log( a )   // 2
  2. 函数调用时,该提供的参数没有提供。prototype

    function f(a) {
    console.log( a );           // undefined
    }
    f();
  3. 对象属性没有赋值, 该属性为undefinedcode

    var obj = new Person();
    console.log(obj.age);      // undefined
  4. 当函数没有返回值时,默认返回undefined对象

    var f = fn();
    console.log( f );   // undefined

    第一次分享文章,若有错误请斧正😑...ip

    (完)原型链

相关文章
相关标签/搜索