--外功篇-《JavaScript那些事》-02-理解null与undefined--

--外功篇-《JavaScript那些事》-02-理解null与undefined--

null与undefined相似点:

两者在JavaScript中均表示为空,没有值

二者在if条件语句中均表示为false:

var a = null;
var b = undefined;
if(!a) {
	console.log('a is '+ !!a);
}
//a is false
if(!b) {
	console.log('b is '+ !!b);
}
//b is false

相等问题:

两者在“==”时是true,在“===”时是false

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

不同之处

null是一个表示"无"的对象,转为数值时为0;

undefined是一个表示"无"的原始值,转为数值时为NaN。

console.log(Number(null));
//0
console.log(Number(undefined));
//NaN

目前,null和undefined基本是同义的,只有一些细微的差别。

解释(查阅资料后)

null表示“没有该对象”,即该处不应该有值 。

  1. 作为函数的参数,表示该函数的参数不是对象。

  2. 作为对象原型链的终点。

Object.getPrototypeOf(Object.prototype)
// null

undefined表示“缺少值”,此处应该有值,但是还没定义。

  1. 声明过但没有赋值的变量,取值时,其值就等于undefined。

  2. 调用函数时,应该提供的形参参数没有提供,该参数等于undefined。

  3. 一个声明的对象中,没有进行过赋值的属性,取值时,该属性的值为undefined。

  4. 函数没有返回值时,默认返回undefined。

    var i;
    i // undefined
    
    function f(x){console.log(x)}
    f() // undefined
    
    var  o = new Object();
    o.p // undefined
    
    var x = f();
    x // undefined
    

——引用自 阮一峰老师的博客

对于阮一峰老师的注解,自己再去翻阅《JavaScript高级程序设计(第3版)》一书中对于undefined与null的说明,摘取其中部分解释进行理解。

undefined:

使用var声明变量但未对其加以初始化,这个变量的值就是undefined

null:

null值表示一个空的对象指针,在使用typeof操作符进行检测时会返回“object”,如果定义的变量准备在将来用于保存对象,那么最好将变量初始化为null

综上所述:

undefined一般出现在未定义、未赋值的情况下

null则是出现于对象为空的情况

离大侠再近一步!
原文地址:https://www.cnblogs.com/Samo-Li/p/13883846.html