• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
社会优先于个人
博客园    首页    新随笔    联系   管理    订阅  订阅
js 的null和undefined的区别

相同点

  • 进行条件判断时,都是false
  • 都是保存在栈中

区别

  • 类型不一样
typeof(null) // object
typeof(undefined) //undefined
console.log(typeof(null) === 'object')//true
console.log(typeof(undefied) === 'undefined')//true
  • 转换的值不一样
console.log(Number(undefined));//NaN
console.log(Number(11+ undefined));//NaN

console.log(Number(null));//0
console.log(Number(11+ null));//10

何时使用null

  • 需要释放一个对象时,可以将这个对象赋值为null
var a = {
  a:1,
  b:2
};
a = null;

如何产生null

  • 访问不存在的dom节点
console.log(document.getElementById(“#aaaaaaa”));//null
  • object原型链
console.log(Object.prototype.__proto__);//null

如何产生undefined

  • 申明了变量,没有赋值
var a;
console.log(a);//undefined
  • 对象的属性,没有赋值
var obj = {a:1}; 
console.log(obj.age)//undefined
  • 没有提供函数的参数
function add(num){ 
 console.log(num)
}; 
add();//undefined
  • 函数没有返回值
var a = function(){};
console.log(a)//undefined

参考文章

https://blog.csdn.net/qq_37600506/article/details/103089072

posted on 2022-04-25 17:40  社会优先于个人  阅读(38)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3