简体   繁体   中英

How to toggle a boolean?

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:

bool = bool ? false : true;
bool = !bool;

这适用于大多数语言。

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).

bool = bool != true;

其中一种情况。

Let's see this in action:

 var b = true; console.log(b); // true b = !b; console.log(b); // false b = !b; console.log(b); // true

Anyways, there is no shorter way than what you currently have.

I was searching after a toggling method that does the same, except for an inital value of null or undefined , where it should become false .

Here it is:

booly = !(booly != false)
bool === tool ? bool : tool

如果您希望该值在tool (另一个布尔值)具有相同值时保持为真

在您可能将真/假存储为字符串的情况下,例如在 localStorage 中,协议在 2009 年翻转为多对象存储,然后仅在 2011 年翻转回字符串 - 您可以使用 JSON.parse 来解释为布尔值飞:

this.sidebar = !JSON.parse(this.sidebar);

I always liked Boolean value, but nowadays I'm using binary for both convenience and debugging. You can use de consept !key : ++key: --key to toggle, and if you are in any asynchronous function or anytime an error or false true occurs, the value will leak out of 0(zero)/ 1(one) and you can trigger an alert to debug later.

bool = !0;  //true
bool = !1;  //false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM