Javascript 如何切换布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11604409/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to toggle a boolean?
提问by Chris Dutrow
Is there a really easy way to toggle a boolean value in javascript?
有没有一种非常简单的方法可以在javascript 中切换布尔值?
So far, the best I've got outside of writing a custom function is the ternary:
到目前为止,除了编写自定义函数之外,我最好的方法是三元:
bool = bool ? false : true;
回答by Jordan
bool = !bool;
This holds true in most languages.
这适用于大多数语言。
回答by Brock Adams
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:
如果您不介意将布尔值转换为数字(即 0 或 1),则可以使用Bitwise XOR Assignment Operator。像这样:
bool ^= true; //- toggle value.
This is especially good if you use long, descriptive boolean names, EG:
如果您使用长的、描述性的布尔名称 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).
此方法适用于所有(主要)浏览器(以及大多数编程语言)。
回答by Feeco
bool = bool != true;
One of the cases.
其中一种情况。
回答by xameeramir
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.
无论如何,没有比您目前拥有的更短的方法了。
回答by HeyJude
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
.
我正在寻找一种执行相同操作的切换方法,除了初始值null
or undefined
,它应该变成false
.
Here it is:
这里是:
booly = !(booly != false)
回答by Ardhi
bool === tool ? bool : tool
if you want the value to hold true if tool
(another boolean) has the same value
如果tool
(另一个布尔值)具有相同的值,如果您希望该值保持为真