在 JavaScript 中,判断一个变量是否未声明(未定义)需要特别注意,因为直接访问未声明的变量会抛出 ReferenceError
错误。
最安全的方式是使用 typeof
操作符,因为它对未声明的变量操作时不会报错,而是返回 'undefined'
:
// 检测变量是否未声明
if (typeof someVariable === 'undefined') {console.log('变量 someVariable 未声明,或已声明但未赋值');
}
需要注意的是,这种方式无法区分「完全未声明的变量」和「已声明但未赋值的变量」,因为这两种情况 typeof
都会返回 'undefined'
。
如果需要严格区分「未声明」和「已声明但未赋值」,可以结合 try...catch
语句:
function isVariableUndeclared(variableName) {try {// 尝试访问变量,如果未声明会抛出 ReferenceErroreval(variableName);// 如果执行到这里,说明变量已声明(即使未赋值)return false;} catch (e) {// 检查错误类型是否为 ReferenceErrorreturn e instanceof ReferenceError;}
}// 测试
console.log(isVariableUndeclared('undeclaredVar')); // true(未声明)let declaredVar;
console.log(isVariableUndeclared('declaredVar')); // false(已声明但未赋值)
总结:
- 简单场景下,
typeof variable === 'undefined'
是最常用的检测方式 - 严格区分未声明和已声明未赋值时,需要使用
try...catch
配合变量访问操作 - 直接使用
if (someVariable)
或if (window.someVariable)
检测未声明变量会报错(非全局变量时)