null、undefined

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清空
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值