如何使用JavaScript切换布尔值

如何使用JavaScript切换布尔值

可以通过两种方法来切换JavaScript中的布尔值,如下所述:

方法1:使用逻辑非运算符

布尔代数中的逻辑非运算符用于否定表达式或值。将此运算符用于true值将返回false,将其用于false值将返回true。可以利用这个特性来切换布尔值。逻辑非运算符用于在要切换的变量之前,并将结果分配给相同的变量。这将有效地切换布尔值。

语法:

booleanValue = !booleanValue

例如:

<html> 
<head> 
    <title> 
        How to toggle a boolean 
        using JavaScript? 
    </title> 
</head> 
  
<body> 
    <h1 style="color: green"> 
        GeeksforGeeks 
    </h1> 
      
    <b> 
        How to toggle a boolean 
        using JavaScript?  
    </b> 
      
    <p> 
        The boolean is toggled whenever 
        the button is pressed. 
    </p> 
      
    <p> 
        See the console for 
        the output 
    </p> 
  
    <button onclick="toggle()"> 
        Toggle Bool 
    </button> 
      
    <script> 
        let testBool = true; 
          
        console.log('Default value of bool is', 
                                   testBool); 
      
        function toggle() { 
            testBool = !testBool; 
              
            console.log('Toggled bool is', 
                                testBool); 
        } 
    </script> 
</body> 
  
</html> 

输出:

  • 单击按钮一次:

如何使用JavaScript切换布尔值

  • 单击按钮两次:

如何使用JavaScript切换布尔值

方法2:使用三元运算符

三元运算符被用作使用if/else语句的快捷方式。它根据表达式的条件进行决策。它接受三个参数,条件语句,如果条件满足则执行的表达式,以及如果条件不满足则执行的表达式。

要切换的布尔值作为条件传递。如果为真,则给出要执行的表达式为“假”,如果为假,则给出要执行的表达式为“真”。该运算符的结果被赋回给要切换的布尔值。这将有效地切换值,因为真条件将返回假,而假条件将返回真。

语法:

booleanValue = booleanValue? false : true

示例:

<!DOCTYPE html> 
<html> 
  
<head> 
    <title> 
        How to toggle a boolean 
        using JavaScript? 
    </title> 
</head> 
  
<body> 
    <h1 style="color: green"> 
        GeeksforGeeks 
    </h1> 
      
    <b> 
        How to toggle a boolean 
        using JavaScript?  
    </b> 
      
    <p> 
        The boolean is toggled 
        whenever the button is 
        pressed. 
    </p> 
      
    <p> 
        See the console 
        for the output 
    </p> 
  
    <button onclick="toggle()"> 
        Toggle Bool 
    </button> 
      
    <script> 
        let testBool = true; 
        console.log('Default value of bool is', 
                    testBool); 
      
        function toggle() { 
            testBool = testBool ? false : true; 
              
            console.log('Toggled bool is', 
                                testBool); 
        } 
    </script> 
</body> 
  
</html> 

输出:

  • 单击按钮一次:

如何使用JavaScript切换布尔值

  • 单击按钮两次:

如何使用JavaScript切换布尔值

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程