How to toggle a boolean?

两盒软妹~` 提交于 2019-12-17 21:24:21

问题


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;

回答1:


bool = !bool;

This holds true in most languages.




回答2:


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




回答3:


bool = bool != true;

One of the cases.




回答4:


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.




回答5:


bool === tool ? bool : tool

if you want the value to hold true if tool (another boolean) has the same value




回答6:


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)


来源:https://stackoverflow.com/questions/11604409/how-to-toggle-a-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!