如何在 JavaScript 中检查变量是否为布尔值?

front end technologyjavascriptweb development

在本教程中,我们将学习在 JavaScript 中检查变量是否为布尔值。在 JavaScript 中,如果我们使用相等运算符匹配两个具有相同值和不同数据类型的不同变量,它将返回真值。这意味着如果我们将两个变量与真值进行比较,但数据类型不同,例如布尔值和字符串,则会产生肯定的结果。

为了克服这些问题,我们需要在将变量与其他值匹配之前检查变量是否为布尔类型。

用户可以使用以下三种方法来检查变量类型。

  • 使用 typeof 运算符

  • 使用严格相等运算符 (===)

  • 使用 tostring.call() 方法

使用 typeof 运算符

typeof 运算符用于检查 JavaScript 中的变量类型。它返回变量的类型。我们将返回的值与 "boolean" 字符串进行比较,如果匹配,我们可以说变量类型是布尔值。

用户可以使用以下语法使用 typeof 运算符来检查变量是否为布尔类型。

语法

typeof 变量

参数

  • 变量 - 它可以是任何类型的变量。

示例

在下面的示例中,我们检查了不同变量的类型。用户可以在输出中看到结果。

<html> <head> <title>Check if variable is of boolean type</title> </head> <body> <h2>Check if variable is of boolean type in JavaScript using <i> typeof </i> operator.</h2> <h4>output for value true</h4> <div id = "result1"></div> <h4>Output for "true"</h4> <div id = "result2"></div> <script> let result1 = document.getElementById("result1"); let result2 = document.getElementById("result2"); let bool = true; result1.innerHTML = typeof bool; bool = "true"; result2.innerHTML = typeof bool; </script> </body> </html>

在上面的输出中,用户可以看到"true"值,它返回类型字符串,对于 true 值,typeof 运算符返回布尔值。

使用严格相等运算符 (===)

当我们使用严格相等运算符比较两个变量时,它会在 JavaScript 中比较两个变量的值和数据类型。正如用户所知,布尔数据类型有两个值,即 true 和 false,我们将变量与两个布尔值进行比较。如果其中一个匹配条件返回 true,则变量为布尔类型。

语法

按照以下语法使用严格相等运算符检查布尔类型变量。

If( variable === true || variable === false ) {

// 变量为布尔类型。
}

示例

在下面的示例中,我们将 bool name 变量与 true 和 false 布尔值进行了比较。用户可以在输出中看到结果。

<html> <head> <title>Check if variable is of boolean type</title> </head> <body> <h2>Check if variable is of boolean type in JavaScript using <i> strict equality </i> operator.</h2> <div id = "result1"></div> <script> let result1 = document.getElementById("result1"); let bool = true; if (bool === true || bool === false) { result1.innerHTML = "variable bool is type of boolean."; } else { result1.innerHTML = "variable bool is not type of boolean."; } </script> </body> </html>

使用 tostring.call() 方法

在本节中,我们将学习使用 tostring.call() 方法来检查变量是否为布尔类型。它的工作方式与 typeof 运算符类似,但返回不同的字符串,而不仅仅是变量的数据类型。此方法返回类似于 '[object data_type]' 的字符串。

语法

用户可以按照以下语法使用 tostring.call() 方法。

let result = toString.call( variable ) === '[object Boolean]'

参数

  • variable − 它是我们需要检查数据类型的变量。

示例

在下面的示例中,我们使用 tostring.call() 方法检查变量类型并将其与'[ object boolean ]'字符串进行比较。如果两个字符串都匹配,则变量为布尔类型。

<html> <head> <title>Check if variable is of boolean type</title> </head> <body> <h2>Check if variable is of boolean type in JavaScript using <i> tostring.call() </i> method.</h2> <div id = "result1"></div> <script> let result1 = document.getElementById("result1"); let bool = true; if ( toString.call(bool) === '[object Boolean]' ) { result1.innerHTML = "variable bool is type of boolean."; } else { result1.innerHTML = "variable bool is not type of boolean. "; } </script> </body> </html>

在本教程中,我们成功地学会了如何检查变量是否为布尔类型。在第一种方法中,我们使用了 typeof 运算符,它也可以用来检查任何变量的数据类型。

在第三种方法中,我们使用了 tostring.call() 方法,它的作用与 type of 运算符相同。但是,严格相等运算符是最佳解决方案,而不是调用方法。


相关文章