有没有一种非常简单的方法在Javascript中切换布尔值?
到目前为止,除了编写自定义函数之外,我最好的方法是使用三元运算符:
bool = bool ? false : true;
有没有一种非常简单的方法在Javascript中切换布尔值?
到目前为止,除了编写自定义函数之外,我最好的方法是使用三元运算符:
bool = bool ? false : true;
bool = !bool;
这在大多数编程语言中都是正确的。
如果你不介意将布尔值转换为数字(即0或1),你可以使用位异或赋值运算符。如下:
bool ^= true; //- toggle value.
这尤其适用于使用长且描述详细的布尔变量名称,例如:let inDynamicEditMode = true; // Value is: true (boolean)
inDynamicEditMode ^= true; // Value is: 0 (number)
inDynamicEditMode ^= true; // Value is: 1 (number)
inDynamicEditMode ^= true; // Value is: 0 (number)
这对我来说比在每行中重复变量更容易扫描。
这种方法适用于所有(主要的)浏览器(和大多数编程语言)。
bool ^= 1
。 - Kyle Muellerbool === false
或 bool === true
。 这可能会破坏现有的代码,请小心。 - aymericbeaumet让我们来看看实际操作:
var b = true;
console.log(b); // true
b = !b;
console.log(b); // false
b = !b;
console.log(b); // true
无论如何,目前没有比您当前所拥有的更短的方法。
bool = bool != true;
其中一个案例。
我在寻找一种切换方法,它可以将初始值为null
或undefined
的值“切换”为false
。
这就是代码:
booly = !(booly != false)
这是一个老问题,但我认为ES6的更新会很好。
通常我们希望一个切换可以处理一切而不破坏我们的代码。
我们可以使用一个初始值为false
的null
或undefined
值来处理。
const boolToggler = b => !(b ?? false)
let foo
console.log('foo:', foo) // undefined
foo = boolToggler(foo)
console.log('foo:', foo) // true (assumes undefined as 'false')
foo = boolToggler(foo)
console.log('foo:', foo); // false
let fee = null
console.log('fee:', fee) // null
fee = boolToggler(fee)
console.log('fee:', fee) // true (assumes null as 'false')
let faa = true
console.log('faa:', faa) // true
faa = boolToggler(faa)
console.log('faa:', faa); // false
!(b ?? false)
这个表达式是否有点多余,因为它已经被传给了 !
运算符?null
和 undefined
本身就是假值,所以可以用 !b
来达到同样的效果。 - Slackowbool === tool ? bool : tool
如果您希望该值在tool
(另一个布尔值)具有相同值时保持为真
在某些情况下,您可能会将true / false存储为字符串,例如在localStorage中,在2009年协议翻转为多对象存储,然后在2011年又翻转回字符串时 - 您可以使用JSON.parse动态解释为布尔值:
this.sidebar = !JSON.parse(this.sidebar);
sidebar = (sidebar == trueValue) falseValue : trueValue;
。 - alans我一直喜欢布尔值,但现在为了方便和调试,我使用二进制。你可以使用概念 !key : ++key: --key
来切换,如果你在任何异步函数中或者任何时候出现错误或假的真实情况,这个值将会泄漏出0(零)/ 1(一),然后你可以触发一个警报来进行调试。
bool = !bool || true;
来设置一个默认值,我想。 - Jordanundefined
开头,这个方法也能很好地工作。 - goodhyun