Shorthand assignment operator for inverting boolean

前端 未结 1 1372
面向向阳花
面向向阳花 2021-01-28 23:49

There are shorthand operators for the basic arithmetic operators, such as:

x = x+2;
x += 2;

or

y = y*2;
y *= 2;
相关标签:
1条回答
  • 2021-01-29 00:45

    Personally I would just negate the thing the way you've done it. But if it really matters to you, and you can afford to forgo the boolean type, just use the numeric internal representation (true==1, false==0) and bitwise operators to negate it:

    z = true;  // z is type boolean
    z ^= 1;    // z is now false, but its type is number
               // (z == false) evaluates to true and you can still do things like if (z)...
    z ^= 1;    // z is now true again
    
    0 讨论(0)
提交回复
热议问题