Shorthand assignment operator for inverting boolean

前提是你 提交于 2019-12-20 07:15:00

问题


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

x = x+2;
x += 2;

or

y = y*2;
y *= 2;

However, I was wondering if there was any such operator that could simply invert the value of a boolean.

For example, assuming z = true, is there any shorter equivalent to:

z = !z;

I know it can't be just !z, because then it would just return the opposite value of z, but it wouldn't change its value.

I know I'm kind of lazy, but I use this a lot in my code and am trying to optimize it as much as possible. I'd try to avoid repeating variable names as much as possible to keep it cleaner and more elegant.

Also, I'm coding in JavaScript.


回答1:


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


来源:https://stackoverflow.com/questions/34971626/shorthand-assignment-operator-for-inverting-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!