简体   繁体   English

布尔反转的简写赋值运算符

[英]Shorthand assignment operator for inverting boolean

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 = true ,则是否有更短的等价于:

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. 我知道它不能只是!z ,因为那样它只会返回z的相反值,但不会改变其值。

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. 另外,我正在用JavaScript编码。

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: 但是,如果这对您确实很重要,并且您可以负担得起boolean类型,则只需使用数字内部表示形式(true == 1,false == 0)和按位运算符即可将其取反:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM