Sometimes I want to combine two statements into one to omit curly braces in conditionals. For example, in PHP, instead of writing
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? Writing x++ && y++
doesn't seem to work.
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/
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
;
Or without 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
returns falsy if x is -1
x++
returns falsy if x is 0
{ }
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.