在JavaScript中,可以像这样声明多个变量:

var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;

...或者像这样:

var variable1 = "Hello, World!",
    variable2 = "Testing...",
    variable3 = 42;

一种方法比另一种更好/更快吗?


当前回答

我相信在我们开始使用ES6之前,使用单一的var声明的方法既不好也不好(如果你有lints和'use strict'的话)。这真的是一种口味偏好。但现在我的情况变了。以下是我对多行声明的一些看法:

Now we have two new kinds of variables, and var became obsolete. It is good practice to use const everywhere until you really need let. So quite often your code will contain variable declarations with assignment in the middle of the code, and because of block scoping you quite often will move variables between blocks in case of small changes. I think that it is more convenient to do that with multiline declarations. ES6 syntax became more diverse, we got destructors, template strings, arrow functions and optional assignments. When you heavily use all those features with single variable declarations, it hurts readability.

其他回答

虽然两者都是有效的,但使用第二种方法会使缺乏经验的开发人员不愿意到处放置var语句,从而导致提升问题。如果每个函数只有一个var,在函数的顶部,那么从整体上调试代码会更容易。这可能意味着声明变量的行不像某些人希望的那样显式。

我觉得这种权衡是值得的,如果这意味着让开发者不再在任何他们喜欢的地方使用“var”。

人们可能会抱怨JSLint,我也一样,但是很多JSLint并不是为了修复语言的问题,而是为了纠正编码员的坏习惯,从而防止他们编写的代码出现问题。因此:

在具有块作用域的语言中,通常建议在第一次使用变量的位置声明变量。但是因为JavaScript没有块作用域,所以更明智的做法是在函数的顶部声明函数的所有变量。建议每个函数使用一个var语句。”——http://www.jslint.com/lint.html范围

避免使用单语句版本(单var)的另一个原因是调试。如果在任何赋值行中抛出异常,堆栈跟踪只显示这一行。

如果使用逗号语法定义了10个变量,则无法直接知道哪个变量是罪魁祸首。

单个语句版本没有这种歧义。

var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;

比:

var variable1 = "Hello, World!",
    variable2 = "Testing...",
    variable3 = 42;

但它们做的事情是一样的。

对于组织来说,每个作用域使用一个var语句是很常见的。所有“作用域”都遵循类似的模式,使代码更具可读性。此外,引擎会把它们都“吊”到顶部。因此,将声明放在一起可以更紧密地模拟实际发生的情况。

也许像这样

var variable1 = "Hello, World!"
, variable2 = 2
, variable3 = "How are you doing?"
, variable4 = 42;

除了更改第一个或最后一个变量外,它易于维护和读取。