How to toggle a boolean?

后端 未结 6 1254
醉话见心
醉话见心 2020-12-07 07:14

Is there a really easy way to toggle a boolean value in javascript?

So far, the best I\'ve got outside of writing a custom function is the ternary:<

6条回答
  •  心在旅途
    2020-12-07 07:32

    If you don't mind the boolean being converted to a number (that is either 0 or 1), you can use the Bitwise XOR Assignment Operator. Like so:

    bool ^= true;   //- toggle value.
    


    This is especially good if you use long, descriptive boolean names, EG:

    var inDynamicEditMode   = true;     // Value is: true (boolean)
    inDynamicEditMode      ^= true;     // Value is: 0 (number)
    inDynamicEditMode      ^= true;     // Value is: 1 (number)
    inDynamicEditMode      ^= true;     // Value is: 0 (number)
    

    This is easier for me to scan than repeating the variable in each line.

    This method works in all (major) browsers (and most programming languages).

提交回复
热议问题