如何使用JavaScript切换布尔值?

2021年3月13日16:55:51 发表评论 661 次浏览

可以使用以下两种方法在JavaScript切换布尔值

方法1:使用逻辑NOT运算符:布尔代数中的逻辑NOT运算符用于取反表达式或值。在true值上使用此运算符将返回false, 在false值上使用它将会返回true。此属性可用于切换布尔值。在要切换的变量之前使用NOT运算符, 并将结果分配给同一变量。这将有效地切换布尔值。

语法如下:

booleanValue = !booleanValue

例子:

< html >
< head >
     < title >
         How to toggle a boolean
         using JavaScript?
     </ title >
</ head >
  
< body >
     < h1 style = "color: green" >
         lsbin
     </ 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 >

输出如下:

单击一次按钮:

一次按下

单击两次按钮:

两次按

方法2:使用三元运算符:三元运算符用作使用if / else语句的快捷方式。它用于根据表达条件做出决定。它包含三个参数:条件语句, 满足条件时要执行的表达式和不满足条件时要执行的表达式。

将要切换的布尔值作为条件传递。如果为true, 则执行的表达式为" false";如果为false, 则执行的表达式为" true"。该运算符的结果被分配回要切换的布尔值。这将有效地切换值, 因为true条件将返回false, false条件将返回true。

语法如下:

booleanValue = booleanValue? false : true

例子:

<!DOCTYPE html>
< html >
  
< head >
     < title >
         How to toggle a boolean
         using JavaScript?
     </ title >
</ head >
  
< body >
     < h1 style = "color: green" >
         lsbin
     </ 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 >

输出如下:

单击一次按钮:

一次按下2

单击两次按钮:

两次按两次

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: