关于undefined
在JavaScript中,undefined
这个词有多重含义。首字母大写的Undefined
表示的是一种数据类型,首字母小写的undefined
表示的是属于这种数据类型的唯一的一个值。但这两种undefined
都只能存在于文档或规范中,不能存在于JavaScript代码中。
在JavaScript代码中,你看到的undefined
最有可能是全局对象的一个属性,该属性的初始值是就是前面所说的原始值undefined
,还有种情况就是,这个undefined
是个局部变量,就像其他普通变量一样,没有任何特殊性,它的值不一定是undefined
,但通常情况下都是的。下面我们所说的undefined
,都指的是window.undefined
这个属性.
在ES3中(Firefox4之前),window.undefined
就是一个普通的属性,你完全可以把它的值改变成为任意的真值,但在ES5中((Firefox4之后),window.undefined
成了一个不可写,不可配置的数据属性,它的值永远是undefined
。
你可以使用严格相等运算符来判断一个值是否是undefined
:
var x; if (x === undefined) { // 执行到这里 } else { // 不会执行到这里 }
注: 这里必须使用严格相等运算符===
,而不能使用普通的相等运算符==
,因为x == undefined
成立还可能是因为x
为null
,在JavaScript中null==undefined
是返回true
的.
另外,还可以使用typeof
来判断:
var x; if (typeof x === 'undefined') { // 执行到这里 }
有时必须使用typeof
的原因是,如果一个变量根本没有被声明,只有使用typeof
判断才不会报错,用相等运算符判断会抛出异常.
// x没有被声明过 if (typeof x === 'undefined') { // 不会报错 // these statements execute } if(x === undefined){ // 抛出ReferenceError异常 }
不过如果要检测的变量是个全局变量,可以不使用typeof
.可以通过检测全局对象的同名属性来代替:
// x可能没有被声明过,但如果已经声明了的话,x是个全局变量 if (window.x === undefined) { // 即使window.x不存在,也不会报错 // 可能会执行到这里 } if(x === undefined){ // 如果window.x不存在,则会抛出ReferenceError异常 }
关于null
null
是一个 JavaScript 字面量,而不是全局对象的一个属性(undefined
是全局对象的一个属性),表示空值(null 或者 “空” 值),即没有对象被呈现(no object value is present)。它是 JavaScript 原始值 之一。在 APIs 中,null
常被放在期望一个对象,但是不引用任何对象的参数位置。当检测 null
或 undefined
时,注意相等(==
)与全等(===
)两个操作符的区别 (前者会执行类型转换)。
// foo does not exist, it is not defined and has never been initialized: > foo "ReferenceError: foo is not defined" // foo is known to exist now but it has no type or value: > var foo = null; foo "null"
null 与 undefined 的不同点:
undefined
表示一个变量没有被声明,或者被声明了但没有被赋值(未初始化),一个没有传入实参的形参变量的值为undefined
,如果一个函数什么都不返回,则该函数默认返回undefined;
null
是一个表示“没有值”的值;- Javascript将未赋值的变量默认值设为
undefined;
- Javascript从来不会将变量设为
null
。它是用来让程序员表明某个用var
声明的变量时没有值的; undefined
不是一个有效的JSON,而null
是;undefined
的类型(typeof)是undefined;
null
的类型(typeof)是object
. ;- 它们都是基本类型;
- 他们都是falsy (
Boolean(undefined)
->// false,Boolean(null)
->// false); - 你可以这样判断一个变量是否是undefined。
typeof variable === "undefined";
- 你可以这样判断一个变量是否是
null
。variable === null
; - 双等号比较时它们相等(
null==undefined
->// true),但三等号比较时不相等(null===undefined
->// false);
2017年05月12日补充:
有朋友QQ群问我 not defined,NaN,undefined和null的区别,所以在这里补充一下。
not defined
有时候我们经常会在控制台中看到类似的错误:Uncaught ReferenceError: *** is not defined
这里的 not defined
表示未定义,或者说没找到这个变量。 会报错!
NaN
NaN 属性用于引用特殊的非数字值。NaN 不是常量,可以使用 isNaN()
来判断一个值是否是数字。原因是 NaN 与所有值都不相等,包括它自己。
例如:
//没定义 foo 时,直接使用 > foo //=> "ReferenceError: foo is not defined" // 定义 foo ,不赋值 > var foo; foo //=> undefined foo + 3 //=> NaN // foo 定义为 null > var foo = null; foo //=> null
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂