在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;
一种方法比另一种更好/更快吗?
当前回答
ECMAScript 2015引入了解构赋值,效果非常好:
[a, b] = [1, 2]
A等于1 b等于2。
其他回答
我相信在我们开始使用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.
正如每个人都说的,这主要是偏好和可读性,但我将在这个帖子上发表评论,因为我没有看到其他人分享这样的想法
我认为这个问题的答案很大程度上取决于你所设置的变量以及它们之间的关系。我尝试着基于我所创造的变量是否相关而保持一致;我的偏好大致是这样的:
对于不相关的变量
我把它们排成一行,这样以后可以很容易地移动它们;我个人从来不会以其他方式声明不相关的项目:
const unrelatedVar1 = 1;
const unrelatedVar2 = 2;
const unrelatedVar3 = 3;
对于相关的东西(实用程序)
如果我要创建一个新变量,我将其声明为一个块——这提示属性属于一起
const
x = 1,
y = 2,
z = 3
;
// or
const x=1, y=2, z=3;
// or if I'm going to pass these params to other functions/methods
const someCoordinate = {
x = 1,
y = 2,
z = 3
};
对我来说,这更符合解构:
const {x,y,z} = someCoordinate;
这样做会让人觉得很笨拙(我不会这么做)
const x = someCoordiante.x;
const y = someCoordiante.y;
const z = someCoordiante.z;
相关事宜(建筑)
如果用同一个构造函数创建了多个变量,我通常也会将它们分组在一起;我个人觉得这样更有可读性
而不是(我通常不这么做)
const stooge1 = Person("moe");
const stooge2 = Person("curly");
const stooge3 = Person("larry");
我通常会这样做:
const [stooge1, stooge2, stooge3] = ["moe", "curly", "larry"].map(Person);
我说通常是因为如果输入参数足够长,这会变得不可读,我会把它们分开。
我同意其他人关于严格使用的评论
除了可维护性,第一种方法消除了意外创建全局变量的可能性:
(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
}());
我认为这是个人喜好的问题。我喜欢用下面的方法做这件事:
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 */;
第一种方法更容易维护。每个声明都是单行上的单个语句,因此可以轻松地添加、删除和重新排序声明。
对于第二种方法,删除第一个或最后一个声明是很烦人的,因为它们分别从var关键字开始并以分号结束。每次添加新声明时,必须将最后一行中的分号替换为逗号。