在JavaScript中,可以像这样声明多个变量:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
...或者像这样:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
一种方法比另一种更好/更快吗?
在JavaScript中,可以像这样声明多个变量:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
...或者像这样:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
一种方法比另一种更好/更快吗?
当前回答
第二种方法的主要问题是,到目前为止还没有IDE支持这种风格。 你不能折叠这些结构。
其他回答
我相信在我们开始使用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.
有c背景的人肯定会使用第二种方法
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
上面的方法看起来更像c语言
这只是个人喜好的问题。这两种方式之间没有区别,只是如果去掉空白,第二种形式节省了一些字节。
我唯一的,也是最重要的,逗号的用法是在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");
在语言之间切换,我一时拿不准。
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
比:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
但它们做的事情是一样的。