JavaScript速记版本可以反转布尔值? [英] JavaScript shorthand version to invert boolean?

查看:429
本文介绍了JavaScript速记版本可以反转布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道,下面是否有速记版本?

I was just wondering, is there a shorthand version of the following?

myBool = !myBool;


我问,因为这样我必须两次输入变量.

谢谢.


I''m asking because this way I have to enter the variable twice.

Thanks.

推荐答案

您对同一变量进行了读取和写入,但不会比已经获得的代码短.例如,加上:
You do a read and a write to the same variable but it won''t get any shorter than the code you already got. With addition for example it would be:
myInt += myInt 




or

myInt++ 


加一个.

当您使用带有布尔值的javascript将其应用时,如下所示:


to add one.

When you apply this in javascript with a bool, like this:

var x = true;
x++;


它只会变成2,因此数据类型已更改.在c/c ++中,可以创建这样的朋友运算符...但是对于javascript,这是不可能的.

祝您好运!


it simply will become 2, so the data type has changed. In c/c++ it would be possible to create such a friend operator... but for javascript this isn''t possible.

Good luck!


通常,您将布尔反转,因为您将在某个处于反转状态的地方使用它.与其将布尔值倒置并将其分配回自己,不如在其他地方使用倒置的版本.所以代替这个:
Usually, you invert a bool because you are going to be using it somewhere with its inverted state. Rather than inverting the bool and assigning it back to itself, just use the inverted version elsewhere. So instead of this:
myBool = !myBool;
someFunction(myBool);


请执行以下操作:


Do this:

someFunction(!myBool);


当然,如果您有这样的话,那是没有意义的:


Of course, that doesn''t make sense if you have something like this:

if(someCondition) {
    myBool = !myBool;
}
// Lots of code that uses myBool.


在这种情况下,只需将其吸干并输入反转布尔值所需的大量代码即可. :rolleyes:


In that case, just suck it up and type the massive amount of code required to invert the bool. :rolleyes:


这篇关于JavaScript速记版本可以反转布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆