在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;
一种方法比另一种更好/更快吗?
当前回答
避免使用单语句版本(单var)的另一个原因是调试。如果在任何赋值行中抛出异常,堆栈跟踪只显示这一行。
如果使用逗号语法定义了10个变量,则无法直接知道哪个变量是罪魁祸首。
单个语句版本没有这种歧义。
其他回答
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
比:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
但它们做的事情是一样的。
ECMAScript 2015引入了解构赋值,效果非常好:
[a, b] = [1, 2]
A等于1 b等于2。
第一种方法更容易维护。每个声明都是单行上的单个语句,因此可以轻松地添加、删除和重新排序声明。
对于第二种方法,删除第一个或最后一个声明是很烦人的,因为它们分别从var关键字开始并以分号结束。每次添加新声明时,必须将最后一行中的分号替换为逗号。
我相信在我们开始使用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语言