惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
Engineering at Meta
Engineering at Meta
GbyAI
GbyAI
MongoDB | Blog
MongoDB | Blog
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC
U
Unit 42
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Apple Machine Learning Research
Apple Machine Learning Research
M
MIT News - Artificial intelligence
人人都是产品经理
人人都是产品经理
Hugging Face - Blog
Hugging Face - Blog
MyScale Blog
MyScale Blog
小众软件
小众软件
博客园 - 三生石上(FineUI控件)
N
Netflix TechBlog - Medium
阮一峰的网络日志
阮一峰的网络日志
博客园 - Franky
Recent Announcements
Recent Announcements
A
About on SuperTechFans
Stack Overflow Blog
Stack Overflow Blog
The GitHub Blog
The GitHub Blog
D
Docker
H
Hackread – Cybersecurity News, Data Breaches, AI and More

博客园 - 苔苔以苔苔以苔

笔记本连接无线网络,提示受限 js中typeof(var) !==和typeof(var) !=的区别 【已验证】帝国cms 里 栏目列表模板获取同级栏目 mysql如何修改导入数据库文件大小限制 错误分析及解决办法---MySQL server has gone away IIS支持flv文件,或者映射其他扩展名到指定的文件类型 qq登录整合帝国cms+ucenter后会提示用户名不合法 JQuery使用getJSON跨域调用数据 php中删除超链接的正则表达式 MySql中distinct的用法 更改表自动递增值的sql 删除文件bom的php代码 win2003系统+IIS6下,经常出现w3wp.exe和sqlserver.exe的内存占用居高不下 如何添加修改uchome创始人 忘记Ucenter创始人密码的最快速解决方法 因为做QQ登录用到session,没想就报错了 匹配中文字符的正则表达式 MySQL字符串相加函数如何运行?似曾相识还是记一笔吧 js获取当前域名及当前页面网址
JS中Null与Undefined的区别
苔苔以苔苔以苔 · 2012-04-19 · via 博客园 - 苔苔以苔苔以苔

在JavaScript中存在这样两种原始类型:Null与Undefined。这两种类型常常会使JavaScript的开发人员产生疑惑,在什么时候是Null,什么时候又是Undefined?

Undefined类型只有一个值,即undefined。当声明的变量还未被初始化时,变量的默认值为undefined。
Null类型也只有一个值,即null。null用来表示尚未存在的对象,常用来表示函数企图返回一个不存在的对象。

js 代码

  1. var oValue;  
  2. alert(oValue == undefined); //output "true"  


这段代码显示为true,代表oVlaue的值即为undefined,因为我们没有初始化它。

js 代码

  1. alert(null == document.getElementById('notExistElement'));  


当页面上不存在id为"notExistElement"的DOM节点时,这段代码显示为"true",因为我们尝试获取一个不存在的对象。

js 代码

  1. alert(typeof undefined); //output "undefined"  
  2. alert(typeof null); //output "object"  


第一行代码很容易理解,undefined的类型为Undefined;第二行代码却让人疑惑,为什么null的类型又是Object了呢?其实这是JavaScript最初实现的一个错误,后来被ECMAScript沿用下来。在今天我们可以解释为,null即是一个不存在的对象的占位符,但是在实际编码时还是要注意这一特性。

js 代码

  1. alert(null == undefined); //output "true"  


ECMAScript认为undefined是从null派生出来的,所以把它们定义为相等的。但是,如果在一些情况下,我们一定要区分这两个值,那应该怎么办呢?可以使用下面的两种方法。

js 代码

  1. alert(null === undefined); //output "false"  
  2. alert(typeof null == typeof undefined); //output "false"  


使用typeof方法在前面已经讲过,null与undefined的类型是不一样的,所以输出"false"。而===代表绝对等于,在这里null === undefined输出false。