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

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

...或者像这样:

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

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


当前回答

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

其他回答

可维护性问题可以很容易地通过一些格式化来解决,比如:

let
  my_var1 = 'foo',
  my_var2 = 'bar',
  my_var3 = 'baz'
;

我严格按照个人喜好使用这种格式。当然,对于单个声明,或者它只是把工作搞砸的情况,我跳过了这种格式。

也许像这样

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

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

我认为这是个人喜好的问题。我喜欢用下面的方法做这件事:

   var /* Variables */
            me = this, that = scope,
            temp, tempUri, tempUrl,
            videoId = getQueryString()["id"],
            host = location.protocol + '//' + location.host,
            baseUrl = "localhost",
            str = "Visit W3Schools",
            n = str.search(/w3schools/i),
            x = 5,
            y = 6,
            z = x + y
   /* End Variables */;

我相信在我们开始使用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.

除了可维护性,第一种方法消除了意外创建全局变量的可能性:

(function () {
var variable1 = "Hello, World!" // Semicolon is missed out accidentally
var variable2 = "Testing..."; // Still a local variable
var variable3 = 42;
}());

而第二种方式就不那么宽容了:

(function () {
var variable1 = "Hello, World!" // Comma is missed out accidentally
    variable2 = "Testing...", // Becomes a global variable
    variable3 = 42; // A global variable as well
}());