如何在 JavaScript 中切换布尔值?
在本教程中,我们将学习如何在 javascript 中切换布尔值。此外,我们还将学习如何将其用于需要切换某个状态或值的各种 Web 应用程序功能。
在 JavaScript 中切换布尔值意味着将其值从 true 更改为 false 或反之亦然。在各种情况下切换布尔值都很有用,例如更改布尔值以启动操作或在状态之间或元素的可见性之间切换。
可以使用不同的方法实现切换,例如非运算符、三元运算符或异或运算符。
让我们看一些示例以更好地理解这个概念 -
示例 1:使用非 (!) 运算符
切换布尔值的一种方法是使用非运算符 (!)。非运算符会否定布尔值,将 true 更改为 false 或 false 更改为 true。在本例中,我们将使用非运算符在单击按钮时切换 flag 值。
文件名 - index.html
<html> <head> <title>How to toggle a boolean using JavaScript?</title> <script> function toggleBoolean() { let flag = true; console.log(flag); flag = !flag; // Toggling the boolean console.log(flag); } </script> </head> <body> <h3>Toggle Boolean using NOT Operator</h3> <button onclick="toggleBoolean()">Toggle Boolean</button> </body> </html>
Learn JavaScript in-depth with real-world projects through our JavaScript certification course. Enroll and become a certified expert to boost your career.
输出
结果将类似于下图。
示例 2:使用三元运算符
三元运算符 (?:) 是切换布尔值的另一种方法。在本例中,我们将使用三元运算符来检查 flag 的值。如果为 true,我们将 flag 设置为 false;如果为 false,我们将 flag 设置为 true。
文件名 - index.html
<html> <head> <title>How to toggle a boolean using JavaScript?</title> <script> function toggleBoolean() { let flag = true; console.log(flag); flag = flag ? false : true; // Toggling the boolean console.log(flag); } </script> </head> <body> <h3>Toggle Boolean using ternary Operator</h3> <button onclick="toggleBoolean()">Toggle Boolean</button> </body> </html>
输出
结果将类似于下图。
示例 3:使用 XOR (^) 运算符
XOR(异或)运算符是切换布尔值的另一种技术。如果操作数具有不同的布尔值,则 XOR 运算符返回 true;否则,它返回 false。我们可以通过对具有固定 true 值的布尔变量使用 XOR 运算符来更改其状态。
文件名 - index.html
<html> <head> <title>How to toggle a boolean using JavaScript?</title> <script> function toggleBoolean() { let flag = true; console.log(flag); flag = flag ^ true; // Toggling the boolean console.log(flag ? true : false); } </script> </head> <body> <h3>Toggle Boolean using XOR Operator</h3> <button onclick="toggleBoolean()">Toggle Boolean</button> </body> </html>
输出
结果将类似于下图。
结论
布尔切换是指将变量的值从 true 更改为 false 或从 false 更改为 true。它允许在不同状态之间进行动态切换,并且适用于许多需要切换特定状态的 Web 应用程序功能。我们学习了如何在 javascript 中切换布尔值,并查看了一些解释相同的示例。