如何在JavaScript中翻转布尔变量的值,而不必两次包含变量名?
foobarthings[foothing][barthing] = !foobarthings[foothing][barthing];
不用两次写foobarthings[foothing][barthing]
。
如何在JavaScript中翻转布尔变量的值,而不必两次包含变量名?
foobarthings[foothing][barthing] = !foobarthings[foothing][barthing];
不用两次写foobarthings[foothing][barthing]
。
你目前的方法已经没有比这更短的了。
not
的运算符:var inverse = return !foo;
这是完全有效的。 - J-Cake!
运算符的理解。 - alex你可以这样做:
foo ^= 1
但是这确实在0和1之间切换foo,而不是true和false。
(foo ^= 1) == true
(必须是 ==
而不是 ===
)。 - J-Cakevar value = true;
alert(value);
value ^= true;
alert(value);
这里可能会得到1或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
return !foo;
这真的很简单...
或者你可以这样做 (foo ^= 1) == true
(必须是 == 而不是 ===)
在执行或检查条件的位置,您可以只使用foo和!foo。
foo++
存在,这个想法有点奇怪。难道不能有类似于foo!!
的东西吗? - yellow-saint