javascript 翻转布尔变量的简写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13972887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:21:23  来源:igfitidea点击:

Shorthand for flipping a boolean variable

javascriptbooleanflipshorthand

提问by Chiel ten Brinke

How can I flip the value of a boolean variable in javascript, without having to include the variable name twice? So

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

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

without writing foobarthings[foothing][barthing]twice.

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

回答by alex

There is no shorter way than what you currently have.

没有比您目前拥有的更短的方法了。

回答by Sjoerd

You can do this:

你可以这样做:

foo ^= 1

But this really switches foo between 0 and 1, not true and false.

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

回答by Anujith

var value = true;
alert(value);
value ^= true;
alert(value);?

You could get 1 or 0 here

你可以在这里得到 1 或 0

回答by Jacob Schneider

To flip the value of a boolean variable in JS you need the syntax like this:

要在 JS 中翻转布尔变量的值,您需要这样的语法:

return !foo;

It's really that easy...

真的是那么容易...

Or you can do (foo ^= 1) == true(must be == not ===)

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

回答by Arunkumar Srisailapathi

You can have just foo and !foo in the place where you execute it or check the condition.

您可以在执行它或检查条件的地方只有 foo 和 !foo 。