javaScript-undefined与null类型

undefined与null类型

undefined

undefined 属性用于存放 JavaScript 中未定义的值。

常见出现undefined的场景

  • 使用只声明而未初始化的变量时
1
2
let a;
console.log(a); // undefined
  • 获取一个对象的某个不存在的属性
1
2
3
4
5
let obj = {
name: 'node',
age: 10
}
console.log(obj.sex); // undefined
  • 函数没有返回值,获取返回值
1
2
function func(){}
console.log(func()); // undefined
  • 函数定义了多种参数,调用时参数不足
1
2
3
4
function func1(a, b){
console.log(b);
}
func1(1); // undefined

null

特指对象的值未设置

常见出现null的场景

  • 变量为了保存后面得到的值,前面定义一个变量赋值为null
1
2
3
4
5
let name = null;
function getName(){
return "node"
}
name = getName();
  • javaScript在获取DOM元素时,如果没有获取指定的元素对象,就会返回null
1
document.getElementById("id");    // null
  • 在使用正则表达式进行捕获时,如果没有捕获结果,就会返回null
1
'test'.match(/a/);    // null

undefined和null异同

  1. 相同点
  • 在将两者转换为对象时,都会抛出一个TypeError的异常,也就是引用异常
1
2
3
4
5
let c;
let b = null;

console.log(c.name); // Cannot read property 'name' of undefined
console.log(b.name); // Cannot read property 'name' of null
  • 在不严格相等的情况下,两者相等
1
null == undefined;    // true
  1. 不同点
  • 在typeof检测时,undefined类型的值会返回’undefined’,而null返回object
1
console.log(typeof(undefined), typeof(null));    // undefined object
  • 在进行数值转换时,undefined转换为NaN,而null转换为0
1
console.log(null + 1, undefined + 1);   // 1 NaN