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

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

...或者像这样:

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

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


当前回答

第二种方法的主要问题是,到目前为止还没有IDE支持这种风格。 你不能折叠这些结构。

其他回答

也许像这样

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

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

我唯一的,也是最重要的,逗号的用法是在for循环中:

for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}

我在JavaScript中查看了一下这个是否可以。

即使它是可行的,一个问题仍然是n是否对函数是局部的。

这验证了n是本地的:

a = [3, 5, 7, 11];
(function l () { for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}}) ();
console.log(typeof n == "undefined" ?
  "as expected, n was local" : "oops, n was global");

在语言之间切换,我一时拿不准。

我们可以使用所有的方法,没有必要只选择其中一种。应用不同的方法可以使代码更易于阅读。

我将展示我Vue.js 3项目中的一个真实例子:

示例1

const [store, route] = [useStore(), useRoute()]
        
const    
   showAlert = computed(() => store.getters['utils/show']),
   userIsLogged = computed(() => store.getters['auth/userIsLogged']),
   albumTitle = computed(() => store.getters['albums/title']);

示例2

const    
   store = useStore(),
   username = ref(''),
   website = ref(''),
   about = ref('');

const 
   isAppFirstRender = computed(() => store.getters['utils/isAppFirstRender']),
   showToast = ref(false);

正如你在上面看到的,我们可以有一小块变量声明。没有必要声明大块。假设我有12个变量,我可以以一种有意义或看起来更容易阅读的方式将它们分组,而不需要冗长:

const
  numberOne = 5,
  numberTwo = 10,
  numberThree = 15;

const
  stringOne = 'asd',
  stringTwo = 'asd2',
  stringThree = 'asd3';

let [one, two, three] = [1,2,3]

当然,每个人都有自己的风格。这是我个人的偏好,混合使用所有方法。

我个人不喜欢冗长。我喜欢有它所需要的而不是更多的代码。

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

比:

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

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

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

(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
}());