Shorthand for flipping a boolean variable

前端 未结 5 1363
礼貌的吻别
礼貌的吻别 2021-02-01 03:13

How can I flip the value of a boolean variable in javascript, without having to include the variable name twice? So

foobarthings[foothing][barthing] = !foobarthi         


        
相关标签:
5条回答
  • 2021-02-01 03:48

    You can do this:

    foo ^= 1
    

    But this really switches foo between 0 and 1, not true and false.

    0 讨论(0)
  • 2021-02-01 03:51

    There is no shorter way than what you currently have.

    0 讨论(0)
  • 2021-02-01 03:54
    var value = true;
    alert(value);
    value ^= true;
    alert(value);​
    

    You could get 1 or 0 here

    0 讨论(0)
  • 2021-02-01 03:58

    To flip the value of a boolean variable in JS you need the syntax like this:

    return !foo;
    

    It's really that easy...

    Or you can do (foo ^= 1) == true (must be == not ===)

    0 讨论(0)
  • 2021-02-01 04:03

    You can have just foo and !foo in the place where you execute it or check the condition.

    0 讨论(0)
提交回复
热议问题