如何在JavaScript中检查空、未定义或空白变量?
在本教程中,我们将学习如何在JavaScript中检查空、未定义或空白变量。 没有特别的内置库函数来检查变量是否为未定义或空。但是,我们可以使用一些运算符,例如typeof运算符和等号运算符来检查变量。
在继续本教程之前,让我们澄清一下空、未定义或空白变量之间的区别。
空值 VS 未定义
我们可以说空值和未定义变量几乎相同,但并不完全一样。
未定义变量 - 它是在程序中未声明的变量,编译器对该变量一无所知。
空值变量 - 它是一个已声明的变量,但我们尚未为其赋值。
空值变量的类型是对象,当我们不为空值变量赋值时,它会自动赋值为'undefined'。我们也可以故意将空值赋给变量以使其保持为空,也称为空值变量。下面,用户可以看到空值和未定义的值相同,但数据类型不同。
let result = null == undefined // returns true let result = null === undefined // returns false
空白变量与不包含任何值的空值变量相同。
使用严格相等运算符 (===) 检查空值变量
在这种方法中,我们将使用严格相等运算符来检查变量是否为空、空或未定义。如果我们在声明变量时不为其赋值,JavaScript编译器会将其赋值为'undefined'值。因此,我们可以检查如果变量包含空值或未定义值,则意味着我们有一个空值变量。
语法
if (variable == null || variable === 'undefined') {
// variable is undefined or null
}
示例
在下面的示例中,我们声明了两个变量。在第一个变量中,我们赋予了空值,在另一个变量中,我们没有赋值。我们正在使用上述方法检查它是否为空,用户可以在输出中看到结果。
<html> <body> <h2>Check for variable is undefined or null using <i>strict equality operator</i></h2> <h4>output for let var1 = null;</h4> <div id = "output1"></div> <h4>output for let var1;</h4> <div id = "output2"> </div> <script> let output1 = document.getElementById("output1"); let output2 = document.getElementById("output2"); function checkVar( variable ) { if (variable == null || variable === 'undefined') { return " varaible is undefined or null; " } else { return " variable is properly defined and its value is " + variable; } } let var1 = null; let var2; output1.innerHTML = checkVar(var1); output2.innerHTML = checkVar(var2); </script> </body> </html>
使用typeof运算符
当变量未定义时,这意味着该变量未声明。用户不能像上述方法那样在'if-else'条件语句中使用它。要检查未声明变量的类型,可以使用typeof运算符。typeof运算符将变量作为操作数并返回变量类型。作为typeof的操作数,我们也可以使用未声明的变量。
语法
let type = typeof ( variable ) // returns ‘undefined’ for undeclare variable.
示例
在下面的示例中,我们创建了一个变量并为其赋予了空值。我们使用带有空值变量的typeof运算符,它返回'object'。我们还使用typeof运算符与第二个变量一起使用,该变量未声明;它返回'undefined'。
<html> <head> <title>Check for variable is undefined or null in JavaScript.</title> </head> <body> <h2>Check for variable is undefined or using <i> typeof operator</i>. </h2> <h4>output for let var1 = null;</h4> <div id = "output1"> </div> <h4>output for undeclared variable;</h4> <div id = "output2"></div> <script> let output1 = document.getElementById("output1"); let output2 = document.getElementById("output2"); let var1 = null; output1.innerHTML = typeof ( var1 ); output2.innerHTML = typeof ( var2 ); // checking the type of undeclared variable </script> </body> </html>
在上面的输出中,用户可以看到typeof运算符为null变量返回对象数据类型。
我们学习了如何检查变量是否未定义或为空。空值和未定义变量之间的区别在于这两个变量的数据类型;空值变量是对象类型,未定义是未定义数据类型。
如果用户正在检查空值变量,则可以使用第一种方法使用if-else条件语句。要检查未声明的变量,用户必须使用第二种方法。否则,当我们使用未声明的变量时,JavaScript代码会报错。
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP