Shorthand for flipping a boolean variable

和自甴很熟 提交于 2019-12-03 04:50:40

问题


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

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

without writing foobarthings[foothing][barthing] twice.


回答1:


There is no shorter way than what you currently have.




回答2:


You can do this:

foo ^= 1

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




回答3:


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

You could get 1 or 0 here




回答4:


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

return !foo;

It's really that easy...

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




回答5:


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



来源:https://stackoverflow.com/questions/13972887/shorthand-for-flipping-a-boolean-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!