JavaScript中 null 和 undefined 的区别

86 阅读2分钟

image.png

undefined/null

undefined:

对声明但未赋值的变量返回类型为 undefined 表示值未定义。

基本类型 let a=''

num=num||5;赋初始值

null:

引用类型 let f={}

null 用于定义一个空对象,即如果变量要用来保存引用类型,可以在初始化时将其设置为 null

undefined/null的区别?

有着不同的语义和场景,但又表现出较为相似的行为。

JS 中的 undefined 和 null 的区别有:

  1. 相等但不全等:
	null == undefined	// true
	null === undefined 	// false

实际上,undefined 值是派生自 null 值的,

可以理解为 null 和 undefined 都代表着无效的值,所以二者相等,

但由于是两种不同的原始数据类型,所以不全等。

typeof undefined	// undefined
typeof null		// object
  1. 在数字运算中被转换为 number 类型的值不同
let a = 10 + null;
console.log(a);	// 10
let b = 10 + undefined;
console.log(b);	// NaN

注:有关加法运算中的隐式类型转换,可参考 “加号 +” 的运算原理(详细!!!)
相同点:
都是原始类型的值,保存在栈中变量本地
何时使用:
null当使用完一个比较大的对象时,需要对其进行释放内存时,设置为null;

var arr=["aa","bb","cc"];
arr=null;//释放指向数组的引用

额外补充的知识
数组进行相等比较是一个怪物,看下面的例子:

[] == ''   // -> true
  [] == 0    // -> true
  [''] == '' // -> true
  [0] == 0   // -> true
  [0] == ''  // -> false
  [''] == 0  // -> true
  [null] == ''      // true
  [null] == 0       // true
  [undefined] == '' // true
  [undefined] == 0  // true

  [[]] == 0  // true
  [[]] == '' // true

  [[[[[[]]]]]] == '' // true
  [[[[[[]]]]]] == 0  // true

  [[[[[[ null ]]]]]] == 0  // true
  [[[[[[ null ]]]]]] == '' // true

  [[[[[[ undefined ]]]]]] == 0  // true
  [[[[[[ undefined ]]]]]] == '' // true

个人理解:
以上例子可以理解为,在比较过程中, [] 、[null] 和 [undefined] 都隐式转换为 '';
对于最里层的 [] ,不管外层嵌套多少个 [] ,最终都可看成只有最里层一个 [] 。

作者:deepCode 链接:juejin.cn/post/719767…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。