首页 文章

在javascript中切换布尔值

提问于
浏览
330

有没有一种非常简单的方法来切换 javascript 中的布尔值?

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

bool = bool ? false : true;

6 回答

  • 3
    bool = !bool;
    

    这在大多数语言中都适用 .

  • 1

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

    bool ^= true;   //- toggle value.
    

    如果你使用长的描述性布尔名称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)
    

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

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

  • 731
    bool = bool != true;
    

    其中一个案例 .

  • 71

    让我们看看这个行动:

    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.

  • 6
    bool === tool ? bool : tool
    

    如果你想让值保持为真,如果 tool (另一个布尔值)具有相同的值

  • 1

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

    这里是:

    booly = !(booly != false)
    

相关问题