在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 hey = 23;
var hi = 3;
var howdy 4;
但是这种方法占用的空间和代码行数更少:
var hey=23,hi=3,howdy=4;
它是节省空间的理想选择,但是让JavaScript压缩器为您处理它。
其他回答
这只是个人喜好的问题。这两种方式之间没有区别,只是如果去掉空白,第二种形式节省了一些字节。
我相信在我们开始使用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 /* 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 */;
“内聚优于耦合”的概念可以更广泛地应用,而不仅仅是对象/模块/函数。它还可以用于以下情况:
OP建议的第二个示例将所有变量耦合到同一个语句中,这使得不可能在不破坏东西的情况下将其中一行移动到其他地方(高耦合)。他给出的第一个例子使得变量分配彼此独立(低耦合)。
从耦合:
低耦合通常是结构良好的计算机系统和良好设计的标志,当与高内聚相结合时,可以支持高可读性和可维护性的总体目标。
所以选择第一个。
是一个很好的特性。没有理由逃避。随着技术的发展,我们也必须自我进化。这个特性在Perl等一些语言中已经存在很长时间了。例如构建WebGL网格,新的javascript样式
//initialize vertices with some calculated points
[verts[ix], verts[iy], verts[iz]] = ps[0];
[verts[ix + 3], verts[iy + 3], verts[iz + 3]] = ps[1];
[verts[ix + 6], verts[iy + 6], verts[iz + 6]] = ps[2];
//initializing normals with cross products
[norms[ix], norms[iy], norms[iz]] = cr;
[norms[ix + 3], norms[iy + 3], norms[iz + 3]] = cr;
[norms[ix + 6], norms[iy + 6], norms[iz + 6]] = cr;
事实上,老式的代码更难调试,到目前为止也更难理解和发现任何bug。这个样本过于简化了。大量重复的例程阻碍了真正的逻辑,使代码看起来像某种魔法。和上面一样,不过是古风:
//initialize vertices with some calculated points
verts[ix] = ps[0][0];
verts[iy] = ps[0][1];
verts[iz] = ps[0][2];
verts[ix + 3] = ps[1][0];
verts[iy + 3] = ps[1][1];
verts[iz + 3] = ps[1][2];
verts[ix + 6] = ps[2][0];
verts[iy + 6] = ps[2][1];
verts[iz + 6] = ps[2][2];
//initializing normals with cross products
norms[ix] = cr[0];
norms[iy] = cr[1];
norms[iz] = cr[2];
norms[ix + 3] = cr[0];
norms[iy + 3] = cr[1];
norms[iz + 3] = cr[2];
norms[ix + 6] = cr[0];
norms[iy + 6] = cr[1];
norms[iz + 6] = cr[2];
注意,在迁移新样式的代码时,我不仅大量删除了大块的例程代码。我很容易就发现了那些逃避了大量代码审查的不一致之处,这只是因为我让代码更容易可视化,更简洁,更面向逻辑,更不面向例程。