如何在 JavaScript 中检查变量是否已定义?


在本教程中,我们将学习如何检查变量的存在,这意味着在JavaScript中变量是否已声明和初始化。在许多情况下,JavaScript 程序员需要检查变量是否存在。否则,如果我们在未声明或定义的情况下使用它,它将抛出引用错误。

例如,程序员已定义变量且未初始化。程序员希望通过从 API 调用中获取的数据来更改变量的值。假设由于 API 调用期间发生某些错误,未初始化变量的值未更新。如果程序员尝试在未检查其值的情况下访问未初始化的变量,它将抛出错误。

在我们继续之前,让我们澄清一下 已定义未定义以及变量之间的区别。

Const data = 10; //variable is declared and defined (initialized with value 10)
Const data; //variable is declared but its value is undefined.
Const data = null; // declared and defined (initialized with "null" value).
data = 10; // undeclared but defined (initialized with 10).
data // undeclared and undefined, type of the variable is undefined

因此,现在用户可以清楚地理解,如果变量未初始化,则其默认值为“未定义”。如果我们用“”值初始化变量,我们可以称其为空变量。如果用户在代码中使用未定义或空变量,他们必须面对错误。

我们有不同的方法来检查变量是否为“未定义”。

  • 使用typeof运算符
  • 使用if 语句
  • 使用window.hasOwnProperty()方法
  • 使用try/catch

使用 typeof 运算符

typeof运算符有助于获取任何变量的数据类型。对于未定义的变量,typeof 运算符返回字符串“undefined”。我们可以使用字符串相等性(“===”)运算符,并将从 typeof 运算符返回的值与“undefined”字符串进行比较,并检查变量是否存在。

语法

用户可以按照以下语法使用 typeof 运算符。

typeof variable_name

参数

  • variable_name − 它可以是任何我们想要检查是否未定义的变量。

通常,如果我们使用未定义的变量作为typeof 变量的操作数,即“typeof undefined_variable”,它不会抛出错误,但如果我们在代码中的任何其他地方使用它,它将抛出错误。

示例 1

以下示例演示了如何使用 typeof 运算符检查变量是否已定义 未定义。变量 age 已声明但未赋值,因此它已定义。

<html>
<head>
   <title> Check if variable is defined or not </title>
</head>
<body>
   <h2>The <i>typeof</i> operator: Check if variable is defined or not</h2>
   <div id="contentDiv"></div>
   <script type="text/javascript">
      let age = 20;
      let contentDiv = document.getElementById("contentDiv");
      if (typeof age === "undefined") {
         contentDiv.innerHTML = " variable <i> age </i> is undefined. ";
      } else {
         contentDiv.innerHTML = "Variable <i> age </i> is defined. ";
      }
   </script>
   <p> Here the variable <i>age</i> is declared with value 20. </p>
</body>
</html>

在上面的输出中,用户可以看到我们已声明“age”变量,并且其值初始化为 20,因此它输出为已定义。

尝试使用以下内容运行上述程序 -

var age; // undefined
age = 20; // defined
var age = 20; // defined
var age = null; // defined
age; // Uncaught ReferenceError: age is not defined (in Console)

请参阅这篇文章以了解未定义和未定义之间的区别。

使用 if 语句

我们可以使用if语句检查变量是否“已定义”或“未定义”。您需要使用以下语法进行检查。

语法

if (variable_name === undefined){
   //block of code to be executed.
}

参数

  • variable_name − 它应该是我们要检查是否已定义的变量的名称。

这里variable_name===undefined是if语句的条件。如果 variable_name 未定义,则条件结果为“true”,否则条件结果为“false”。请看下面的例子。

示例 2

<html>
<body>
   <h2>The <i>if</i> statement: Check if variable is defined or not </h2>
   <div id = "contentDiv" > </div>
   <script>
      var rank;
      let contentDiv = document.getElementById("contentDiv" );
      if(rank===undefined){
         contentDiv.innerHTML = " variable <i> rank </i> is undefined. ";
      } else{
         contentDiv.innerHTML = " variablle <i> rank </i> is defined. ";
      }
   </script>
</body>
</html>

在上面的输出中,用户可以看到我们已声明“rank”变量,但其值未初始化,因此它输出为未定义。

使用window.hasOwnProperty()方法

我们可以使用 JavaScript 中的 window 属性访问每个全局定义的变量、对象或函数。“window”充当全局对象以检查任何变量的存在。我们可以为 window 对象调用hasOwnProperty()方法以确认它是否包含该变量。它根据变量是否已定义返回布尔值。

语法

let isUndefined = window.hasOwnProerty('variable_name').

参数

  • variable_name − 它应该是我们要检查是否已定义的变量的名称。

返回值 − 如果 variable_name 存在(已定义或已声明),则返回“true”,否则返回“false

示例 3

以下示例演示了如何使用window.hasOwnProperty()方法检查变量是否未定义。

<html>
<head>
   <title> Check if variable is defined or not </title>
</head>
<body>
   <h2>The <i> window.hasOwnProperty()</i > method</h2>
   <p>Checking the existence of a variable</p>
   <div id="variableDiv"></div>
   <script type="text/javascript">
      // isdefined variable either get true or false value
      var isdefined = window.hasOwnProperty('data');
      let variableDiv = document.getElementById("variableDiv");

      // function to check if variable is undefined or not.
      function checkExistanceOfVar() {
         if (isdefined) {
            variableDiv.innerHTML = " Variable <i> data </i> exist ";
         } else {
            variableDiv.innerHTML = " Variable <i> data </i> doesn't exist ";
         }
      }

      // call the function
      checkExistanceOfVar();
   </script>
</body>
</html>

在上面的输出中,用户可以看到‘data’变量不存在,因此window.hasOwnProerty()方法返回false,控制权转到 else 块。

但是,上述方法不适用于 let 和 const 变量。用户可以使用上述方法检查使用 var 关键字声明的函数和变量的存在。

使用 try/catch 块

通常,我们使用try/catch块来防止我们的代码因未知错误而崩溃。当变量未定义或未初始化时,JavaScript 会返回引用错误。我们可以尝试在 try 块中访问变量,如果发生任何错误或变量未定义,控制权将转到 catch 块,我们可以在那里解决错误。

语法

用户可以按照以下语法使用 try/catch 块。

try{
   let data = res;
} catch ( error ) {
   // control goes here if variable is undefined without
   // completing the try block
}

示例 4

在下面的示例中,我们演示了如何使用 try/catch 块来检查变量是否未定义。

<html>
<head>
   <title> Check if variable is defined or not </title>
</head>
<body>
   <h2>Checking if the variable id defined using the <i>try / catch</i> block.</h2>
   <div id="errorDiv"></div>
   <script type="text/javascript">
      let errorDiv = document.getElementById("errorDiv");
      function checkExistanceOfVar() {
         // using the try/catch block
         try {
            let data = result;
            errorDiv.innerHTML = " <i> result </i> variable exist";
         } catch (error) {
            errorDiv.innerHTML = error;
         }
      }

      // call the function
      checkExistanceOfVar();
   </script>
</body>
</html>

在上面的示例中,我们尝试将未定义结果变量赋值给 data 变量,因此控制权转到 catch 块并输出 ReferenceError。

结论

我们已经看到了三种不同的方法来检查变量是否未定义。第一种方法适用于所有情况。用户只能将第二种方法用于使用“var”关键字声明的变量。在使用第三种方法时,用户需要在 catch 块中指定错误类型。否则,由于其他错误,控制权将转到 catch 块。

更新于: 2022-07-12

3K+ 次浏览

开启你的职业生涯

通过完成课程获得认证

立即开始
广告
© . All rights reserved.