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

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

bool = bool ? false : true;

当前回答

bool = !bool;

大多数语言都是如此。

其他回答

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

this.sidebar = !JSON.parse(this.sidebar);
bool === tool ? bool : tool

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

bool = bool != true;

其中一个案例。

bool = !bool;

大多数语言都是如此。

让我们来看看实际情况:

Var b = true; console.log (b);/ /正确的 B = ! console.log (b);/ /错误 B = ! console.log (b);/ /正确的

无论如何,没有比你现在拥有的更短的路了。