JavaScript检查变量是否存在(已定义/已初始化)

JavaScript检查变量是否存在(已定义/已初始化)

技术背景

在JavaScript开发中,经常需要检查变量是否存在(已定义/已初始化),以避免出现引用错误或进行默认值设置等操作。由于JavaScript的动态类型特性,变量可以在不同阶段具有不同的状态,因此准确检查变量的状态十分重要。

实现步骤

使用typeof操作符

typeof操作符可以检查变量是否为undefined。它的优点是在使用未声明的变量时不会抛出ReferenceError异常。

1
2
3
4
5
6
7
if (typeof variable !== 'undefined') {
// 变量已定义
}

if (typeof variable === 'undefined') {
// 变量未定义
}

考虑null

由于typeof null会返回"object",因此在检查变量时,需要同时考虑undefinednull的情况。

1
2
3
if (typeof variable === 'undefined' || variable === null) {
// 变量未定义或为null
}

使用in操作符检查全局变量

在浏览器环境中,可以使用in操作符检查全局变量是否存在。

1
2
3
4
5
if ("v" in window) {
// 全局变量v已定义
} else {
// 全局变量v未定义
}

检查函数参数是否为undefined

可以定义一个函数来检查函数参数是否为undefined

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function isset(variable) {
return typeof variable !== typeof undefined;
}

var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};

test(a);
// 输出:
// TRUE
// FALSE

使用try-catch

当变量可能根本未定义时(如外部库未加载),可以使用try-catch块来检查,而不会中断代码执行。

1
2
3
4
5
try {
notDefinedVariable;
} catch (e) {
console.log('detected: variable not exists');
}

使用三元运算符设置默认值

可以使用三元运算符在变量未初始化时设置默认值。

1
var dark = typeof darkColor !== typeof undefined ? darkColor : "black";

核心代码

检查变量是否已定义并设置默认值

1
2
var setOrNot = typeof variable !== typeof undefined;
var dark = typeof darkColor !== typeof undefined ? darkColor : "black";

检查函数参数是否为undefined

1
2
3
4
5
6
7
8
9
10
11
function isset(variable) {
return typeof variable !== typeof undefined;
}

var a = '5';
var test = function(x, y) {
console.log(isset(x));
console.log(isset(y));
};

test(a);

使用try-catch块检查变量是否存在

1
2
3
4
5
try {
notDefinedVariable;
} catch (e) {
console.log('detected: variable not exists');
}

最佳实践

  • 优先使用typeof操作符进行变量检查,因为它不会抛出ReferenceError异常。
  • 在需要同时考虑undefinednull的情况时,使用typeof variable === 'undefined' || variable === null
  • 对于全局变量的检查,可以使用"v" in window
  • 在设置默认值时,使用三元运算符可以使代码更简洁。

常见问题

封装检查函数时的引用错误

不能简单地将检查封装在一个函数中,因为不能将不存在的变量传递给函数,否则会抛出ReferenceError异常。

1
2
3
4
5
6
function isset(variable) {
return typeof variable !== typeof undefined;
}

// 会抛出ReferenceError
isset(foo);

undefined的可变性

在JavaScript中,全局的undefined可以被重写,因此直接使用varName !== undefined可能会导致意外结果。建议使用typeof操作符来避免这个问题。

区分undefinednull

null是一个可以赋值给变量的值,表示变量没有特定的值;而undefined是未赋值变量的默认值。在检查时需要注意区分这两种情况。


JavaScript检查变量是否存在(已定义/已初始化)
https://119291.xyz/posts/2025-05-14.javascript-check-if-variable-exists/
作者
ww
发布于
2025年5月14日
许可协议