JavaScript 检查变量的存在性
JavaScript 有一个内置函数,用来检查变量是否已定义 / 初始化或未定义。为此,我们将使用 typeof 运算符。如果变量未初始化,typeof运算符将返回 undefined ;如果变量是有意留空,则运算符将返回 null 。
注意:
- typeof 运算符将检查变量是否已定义。
- typeof 运算符在与未声明的变量一起使用时不会抛出 ReferenceError 异常。
- typeof null 将返回对象。因此,也要检查null。
示例1: 此示例用于检查变量是否已定义。
let GFG_Var;
if (typeof GFG_Var === 'undefined') {
console.log("Variable is Undefined");
}
else {
console.log("Variable is defined and"
+ " value is " + GFG_Var);
}
输出
Variable is Undefined
示例2: 该示例还会检查变量是否已定义。
let GFG_Var = "GFG";
if (typeof GFG_Var === 'undefined') {
console.log("Variable is Undefined");
}
else {
console.log("Variable is defined and"
+ " value is " + GFG_Var);
}
输出
Variable is defined and value is GFG
示例 3: 在这个示例中,我们将检查一个变量是否为空。
let GFG_Var = null;
if (typeof GFG_Var === null) {
console.log("Variable is null");
}
else {
console.log("Variable is defined and value is "
+ GFG_Var);
}
输出
Variable is defined and value is null
极客教程