用 var 或 let 声明的且未赋初值的变量,值会被设定为
undefined
。
试图访问一个未声明的变量或者访问一个使用 let
声明的但未初始化的变量会导致一个 ReferenceError
异常
被抛出:
var a; // a 的值是 undefined console.log("The value of a is " + a);// Uncaught ReferenceError: b is not defined
console.log("The value of b is " + b);// c 的值是 undefined console.log("The value of c is " + c); var c; // Uncaught ReferenceError: x is not defined console.log("The value of x is " + x); let x;
你可以使用
undefined 来判断变量
是否已赋值。以下的代码中,变量input
未被赋值,因而if
条件语句的求值结果是true
。
var input;
if(input === undefined){
doThis();
} else {
doThat();
}
undefined
值在布尔类型环境中会被当作 false。例如,下面的代码将会执行函数
myFunction
,因为数组myArray
中的元素未被赋值:
var myArray = [];
if (!myArray[0]) {
myFunction();
}
数值类型环境中 undefined
值会被转换为 NaN。
var a;
// 计算为 NaN
a + 2;
当你对一个 null
变量求值时,空值 null
在数值类型环境中会被当作0来对待,而布尔类型环境中会被当作 false
。例如:
var n = null;
typeof(n);
// "object"
// The Null type has exactly one value, called null.
console.log(n * 32); // 0