相同和不同之处
undefined和null在if语句中,都会被自动转为false,加!转换为true,相等运算符对于两者比较是相等的。
undefined == null
console.log(typeof undefined);
console.log(typeof null);
null是一个表示"无"的对象,转为数值时为0;undefined是一个表示"无"的原始值,转为数值时为NaN。
var a1= 5 + null;
console.log(a1)
var a2= 5 + undefined;
console.log(a2)
null !== undefined
null === undefined
null == undefined
实际会出现的场景
null
- (1) 利用document.getElementById(‘XXX’) 寻找一个
不存在的元素,将返回null。
console.log(null == document.getElementById('notExistElement'))
Object.getPrototypeOf(Object.prototype)
undefined
- (1)声明了一个
变量,但没有赋值,就等于undefined。
var a
console.log(a) // undefined
- (2) 函数定义了
形参,但没有传递实参,该参数等于undefined。
function f(a) {
console.log(a);
}
f();
- (3)访问对象上
不存在的属性,该属性的值为undefined。
var a = new Object()
a.p
- (4)函数
没有返回值时,默认返回undefined。
var a = f()
a
NaN