用于反转布尔值的简写赋值运算符 [英] Shorthand assignment operator for inverting boolean
问题描述
基本算术运算符有简写运算符,例如:
x = x + 2;
x + = 2;
或
y = y * 2;
y * = 2;
但是,我想知道是否有任何这样的运算符可以简单地反转一个布尔值。
例如,假设 z = true
,是否有更短的等价于:
z =!z;
我知道它不能只是!z
,因为它只返回 z
的相反值,但它不会改变它的值。
<我知道我有点懒,但我在代码中使用了很多,并且尽可能地优化它。我尽量避免重复使用变量名来保持它更干净,更优雅。
另外,我用JavaScript编码。
就个人而言,我会以你的方式否定事情。但是,如果它对你真的很重要,你可以放弃布尔
类型,只需使用数字内部表示(true == 1,false == 0)和按位运营商否定它:
z = true; // z是类型boolean
z ^ = 1; // z现在为false,但其类型为数字
//(z == false)的计算结果为true,您仍然可以执行if(z)...
z ^ = 1; // z现在再次为真
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.
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
这篇关于用于反转布尔值的简写赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!