如何切换布尔值?

时间:2012-07-22 22:10:14

标签: javascript boolean toggle

是否有一种非常简单的方法可以在 javascript 中切换布尔值?

到目前为止,除了编写自定义函数之外,最好的还有三元:

bool = bool ? false : true;

8 个答案:

答案 0 :(得分:787)

bool = !bool;

大多数语言都适用。

答案 1 :(得分:77)

如果您不介意将布尔值转换为数字(即0或1),则可以使用the Bitwise XOR Assignment Operator。像这样:

bool ^= true;   //- toggle value.


如果您使用长的描述性布尔名称E​​G:

,这尤其有用
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)

这比我在每一行中重复变量更容易扫描。

此方法适用于所有(主要)浏览器(以及大多数编程语言)。

答案 2 :(得分:9)

bool = bool != true;

其中一个案例。

答案 3 :(得分:4)

让我们看看这个:



var b = true;

console.log(b); // true

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

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




无论如何,there is no shorter way than what you currently have.

答案 4 :(得分:1)

bool === tool ? bool : tool

如果你希望如果tool(另一个布尔值)具有相同的值,则该值保持为真

答案 5 :(得分:1)

我正在搜索一个相同的切换方法,除了nullundefined的初始值,它应该变为false

这是:

booly = !(booly != false)

答案 6 :(得分:0)

如果您可能将 true/false 存储为字符串,例如在 localStorage 中,协议在 2009 年转为多对象存储,然后仅在 2011 年转回字符串 - 您可以使用 JSON.parse 来解释为即时布尔值:

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

答案 7 :(得分:0)

b^=!0

是我能想到的最短方法,当你需要它是一个布尔值时,然后用它前面的双感叹号检查它!!​​bool

var bool = true; bool^=!0; /*bool is now 0*/ bool=!!bool; /*bool is now false*/