[英]How to combine two JavaScript statements into one
Sometimes I want to combine two statements into one to omit curly braces in conditionals. 有时我想将两个语句合并为一个,以省略条件括号中的花括号。 For example, in PHP, instead of writing
例如,在PHP中,无需编写
if ($direction == 'south-east') {
$x++;
$y++;
}
I would write 我会写
if ($direction == 'south-east') $x++ and $y++;
but is there a way to do that in JavaScript? 但是有没有办法在JavaScript中做到这一点? Writing
x++ && y++
doesn't seem to work. 编写
x++ && y++
似乎无效。
Curly braces aren't that bad, but - in very specific cases - you can enhance your code by using commas : 花括号并没有那么糟糕,但是-在非常特殊的情况下-您可以使用逗号来增强代码 :
if (direction == 'south-east') x++, y++;
Here's the fiddle: http://jsfiddle.net/FY4Ld/ 这是小提琴: http : //jsfiddle.net/FY4Ld/
You can do it like this: 您可以这样做:
var x = 0,
y = 0,
cond = true;
if (cond) ++x && ++y;
Note: This doesn't work if x is -1
; 注意:如果x为
-1
,则此方法不起作用;
Or without if
: 还是没有,
if
:
cond && ++x && ++y;
So your code would look like this: 因此,您的代码如下所示:
if ($direction == 'south-east') $x++ && $y++;
Note that the ++
operators is after the variable that means this won't work if $x
is 0
. 请注意,
++
运算符位于变量之后,这意味着如果$x
为0
,则此操作将无效。
++x
returns falsy if x is -1
如果x为
-1
则++x
返回falsy
x++
returns falsy if x is 0
如果x为
0
则x x++
返回falsy
{ }
that you use does just that - combines statements in one block usable with any flow control statement. 您使用的
{ }
就是这样做的-将一个语句中的语句与任何流控制语句结合使用。 You can place entire block on one line - JS doesn't care about whitespace in this case. 您可以将整个块放在一行上-在这种情况下,JS不在乎空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.