JavaScript—不同环境下undefined的不同值

用 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值