1

我见过很多例子:

var foo = 1, bar = 2, baz = 3;

但是,我可以不做同样的事情var吗?例子:

// Declare at top of block for readability's sake:
var foo, bar, baz;
// ... stuff here ...
// Later in script, I finally get around to initializing above vars:
foo = 1, bar = 2, baz = 3; // Is using commas without var legal?

换句话说,在javascript中有一行我在没有var关键字的情况下初始化/设置多个变量是否合法?我还没有找到任何关于这是否被允许和/或得到很好支持的权威文档。

替代方案是:

foo = 1; bar = 2; baz = 3;

这是促使我提出问题的现实世界的情况:

for (var i = 0, l = haystack.length; i < l; i++) { ... }

...我想将for循环内的变量声明移动到父块的顶层,例如:

var i, l;

// ... stuff here ...

for (i = 0, l = haystack.length; i < l; i++) { ... }

...但我只var在语句开头使用逗号。以上是合法的(?),还是应该是:

var i, l;

// ... stuff here ...

for (i = 0; l = haystack.length; i < l; i++) { ... }

(注意添加的分号。)

4

1 回答 1

4

In javascript you can separate expressions by commas and they will execute left to right, returning the value of the far right expression

So yes you can do this in general and the following is legal syntax.

for (i = 0, l = haystack.length; i < l; i++) { ... }

See more about the comma operator here: MDN Docs

于 2013-03-12T20:01:03.543 回答