将布尔变量取反的简写方式

34

如何在JavaScript中翻转布尔变量的值,而不必两次包含变量名?

foobarthings[foothing][barthing] = !foobarthings[foothing][barthing];

不用两次写foobarthings[foothing][barthing]


3
那实际上相当聪明。从未想过那个。 - Luke
17
考虑到 foo++ 存在,这个想法有点奇怪。难道不能有类似于 foo!! 的东西吗? - yellow-saint
6个回答

32

你目前的方法已经没有比这更短的了。


这并非完全正确,实际上有一个名为not的运算符:var inverse = return !foo; 这是完全有效的。 - J-Cake
2
@JacobSchneider 你发布的代码在语法上是无效的,而且原帖作者已经展示了对于 ! 运算符的理解。 - alex
Anujith用“^=”操作回答了,你为什么认为那不是有效的? - Pixsa

13

你可以这样做:

foo ^= 1

但是这确实在0和1之间切换foo,而不是true和false。


1
但是你可以这样做:(foo ^= 1) == true(必须是 == 而不是 ===)。 - J-Cake

3
var value = true;
alert(value);
value ^= true;
alert(value);​

这里可能会得到1或0


1
这可以被认为是“简写”吗? - alex

0

你可以创建一个带有布尔属性的新构造函数,然后添加一个原型来翻转它

function Bit(bit=false) {
  this._ = bit;
}
Bit.prototype.flip = function() {
  this._ = !this._;
  return this._
}

//example:
var foo = new Bit();
console.log(foo._) //logs false
foo.flip() //flips to true
console.log(foo._); //logs true
console.log(foo.flip()) //flips to false and logs it

-1
要在JS中翻转布尔变量的值,你需要使用以下语法:
return !foo;

这真的很简单...

或者你可以这样做 (foo ^= 1) == true (必须是 == 而不是 ===)


2
问题是关于在赋值和翻转布尔状态时避免重复名称的。 - alex
我只使用变量的名称一次。 - J-Cake
2
用户想将翻转后的值重新赋给同一变量名,而此答案未涉及此问题。 - alex

-3

在执行或检查条件的位置,您可以只使用foo和!foo。


2
不,我需要在其中存储相反的值。 - chtenb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接