null
- 用来定义一个**空对象 **
let a = null
- 定义一个没有确定内容的变量用来保存引用类型,可以在初始化时将其设置为 null。
let myObj = null;
- Null 类型的值只有一个,就是 null。
typeof null // object
null > 0 //false
null == 0 //false
null >= 0 //true
/** < > <= >=比较时会转换为数字 null被返回了 0 所以null >= 0
== 时不会进行类型转换 只有null==null 或者 null==undefined 为true**/
undefined
- Undefined 类型的值只有一个,就是 undefind。
typeof undefined // undefined
undefined > 0 // false
undefined < 0 // false
undefined == 0 // false
/** < > <= >=比较时会转换为数字 undefined被返回了 0 所以null >= 0
== 时不会进行类型转换 只有undefined==null 或者 undefined==undefined 为true**/
//定义后未赋值变量为 undefined
let name;
console.log(name); // undefined
console.log(typeof name); // undefined
//未声明变量为 undefined
console.log(typeof nothing); // undefined
console.log(nothing); // 打印结果:Uncaught ReferenceError: a is not defined
//无返回值函数的返回值为undefined
function foo() {}
console.log(foo()); // 打印结果:undefined
//调用函数未传参为undefined
function foo(name) {
console.log(name);
}
foo(); // 调用函数时,未传参。执行函数后的打印结果:undefined
null和undefined区别
- null 和 undefined 有很大的相似性。看看 null == undefined 的结果为 true 也更加能说明这点。
- 但是 null === undefined 的结果是 false。它们虽然相似,但还是有区别的,其中一个区别是,和数字运算时:
- 任何数据类型和 undefined 运算都是 NaN;
- 任何值和 null 运算,null 可看做 0 运算。
- null 是一个只有一个值的特殊类型,表示一个空对象引用
- 用null清空对象,值为null,但是typeof(即为类型)为对象
- 用undefined清空对象,值为undefined,类型为undefined
- 任何变量都可以通过undefined清空