发布于 4年前

JavaScript undefined与ReferenceError: xxx is not defined

在JavaScript里,为了简便,判断语句常常这样写:

if(abc) {
  //do something
}

变量未声明

假如abc变量没有被声明,但此处会报错:

ReferenceError: abc is not defined

变量已声明,为初始化

示例修改下变为

var abc;

if(abc) {
  console.log("abc is defined");
} else {
  console.log("abc is undefined.");
}

abc已经声明,但没有被初始化。abc的值为undefined。在判断语句里,undefined为false值,正常输出:

abc is undefined.

解决方法

为了避免出现ReferenceError: abc is not defined错误,检查变量是否为undefined时使用typeof操作符

if(typeof abc != 'undefined') {
  //do something
}
©2020 edoou.com   京ICP备16001874号-3