如何将两个JavaScript语句合并为一个

Sop*_*rus 4 javascript

有时我想将两个语句组合成一个以省略条件句中的花括号.例如,在PHP中,而不是写作

if ($direction == 'south-east') {
    $x++;
    $y++;
    }
Run Code Online (Sandbox Code Playgroud)

我会写的

if ($direction == 'south-east') $x++ and $y++;
Run Code Online (Sandbox Code Playgroud)

但有没有办法在JavaScript中做到这一点?写作x++ && y++似乎不起作用.

Jos*_*ber 10

大括号并不是那么糟糕,但是 - 在非常特殊的情况下 - 您可以使用逗号增强代码:

if (direction == 'south-east') x++, y++;
Run Code Online (Sandbox Code Playgroud)

这是小提琴:http://jsfiddle.net/FY4Ld/

  • http://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/ (2认同)