var a = undefined;
var b = null;
if (!a) {
console.log('undefined is false'); // undefined is false
}
if (!b) {
console.log('null is false'); // null is false
}
console.log(isNaN(a)); // true
console.log(isNaN(b)); // false
console.log(a == b); // true
console.log(a === b); // false
console.log(typeof null); // object
console.log(typeof undefined); // undefined
- undefined与null转换为布尔值都为false;
- null 表示一个“无”的对象,转为数值时为0;undefined表示一个“无”的原始值,转换为数字位NaN;
- undefined 从null派生 “==”,认为相等所以输出true;“===”需要比较类型,类型不一致,所以输出false;
1、null 表示没有对象,即该出不应该有值,用法为:
① 作为函数的参数,表示该函数的参数不是对象。
② 作为对象原型链的终点。
2、undefined表示"缺少值",就是此处应该有一个值,但是还没有定义。典型用法是:
① 变量被声明了,但没有赋值时,就等于undefined。
② 调用函数时,应该提供的参数没有提供,该参数等于undefined。
③ 对象没有赋值的属性,该属性的值为undefined。
④ 函数没有返回值时,默认返回undefined。
// 变量声明未初始化
var a;
console.log(a); // undefined
// 函数调用未传参
function f(x) {
console.log(x);
}
f(); // undefined
// 对象未赋属性值
var o = new Object();
console.log(o.p); // undefined
// 函数没有返回值
var x = f();
console.log(x); // undefined
网友评论