是否有一个真正简单的方法来切换一个布尔值在javascript?

到目前为止,除了编写自定义函数之外,我得到的最好的方法是三元函数:

bool = bool ? false : true;

当前回答

bool = bool != true;

其中一个案例。

其他回答

bool = !bool;

大多数语言都是如此。

在你可能将true / false存储为字符串的情况下,例如在localStorage中,协议在2009年翻转为多对象存储,然后在2011年才翻转回字符串-你可以使用JSON。解析来解释布尔值:

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

如果您不介意将布尔值转换为数字(即0或1),则可以使用按位异或赋值操作符。像这样:

bool ^= true;   //- toggle value.

This is especially good if you use long, descriptive boolean names, EG:
let inDynamicEditMode   = true;     // Value is: true (boolean)
inDynamicEditMode      ^= true;     // Value is: 0 (number)
inDynamicEditMode      ^= true;     // Value is: 1 (number)
inDynamicEditMode      ^= true;     // Value is: 0 (number)

对我来说,这比在每行中重复变量更容易扫描。

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

bool = bool != true;

其中一个案例。

bool === tool ? bool : tool

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