JavaScript 变量定义:逗号与分号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3781406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:08:46  来源:igfitidea点击:

JavaScript variable definition: Commas vs. Semicolons

javascriptvariables

提问by Collin Klopfenstein

What are the differences and/or advantages, if any, of using commas when declaring a group of variables rather than semicolons.

在声明一组变量而不是分号时使用逗号有什么区别和/或优点(如果有的话)。

For example:

例如:

var foo = 'bar', bar = 'foo';

versus

相对

var foo = 'bar';
var bar = 'foo';

I know that if you specify the varkeyword on the first variable in the first example it persists across all of the variables, so they both produce the same end result regarding scope. Is it just personal preference, or is there a performance benefit to doing it either way?

我知道,如果您var在第一个示例中的第一个变量上指定关键字,它会在所有变量中持续存在,因此它们都会产生关于作用域的相同最终结果。这只是个人喜好,还是这样做对性能有好处?

采纳答案by Oded

No performance benefit, just a matter of personal choice and style.

没有性能优势,只是个人选择和风格的问题。

The first version is just more succinct.

第一个版本更简洁。



Update:

更新:

In terms of the amount of data going over the wire, of course less is better, however you would need a hell of a lot of removed vardeclarations in order to see a real impact.

就通过网络传输的数据量而言,当然越少越好,但是您需要大量删除var声明才能看到真正的影响。

Minificationhas been mentioned as something that the first example will help with for better minification, however, as Daniel Vassallopoints out in the comments, a good minifier will automatically do that for you anyways, so in that respect no impact whatsoever.

已经提到缩小是第一个示例将有助于更好地缩小的东西,但是,正如Daniel Vassallo在评论中指出的那样,一个好的缩小器无论如何都会自动为你做,所以在这方面没有任何影响。

回答by Felix

After reading Crockford and others, I started to chain my variables with comma exclusively. Then later, I really got annoyed by the Chrome DevTools debugger that wouldn't stop at variable definitions with comma. For the debugger, variable definitions chained with comma are a single statement, while multiple var statements are multiple statements at which the debugger can stop. Therefore, I switched back from:

在阅读 Crockford 和其他人之后,我开始专门用逗号链接我的变量。后来,我真的对 Chrome DevTools 调试器感到恼火,它不会停在带有逗号的变量定义处。对于调试器,用逗号链接的变量定义是单个语句,而多个 var 语句是调试器可以停止的多个语句。因此,我从以下位置切换回来:

var a = doSomethingA,
    b = doSomethignB,
    c = doSomethingC;

To:

到:

var a = doSomethingA;
var b = doSomethignB;
var c = doSomethingC;

By now, I find the second variant much cleaner, not to mention its advantage of solving the debugger issue.

到目前为止,我发现第二个变体更清晰,更不用说它解决调试器问题的优势了。

The "less code through the wire" argument is not persuasive, as there are minifiers.

“通过电线减少代码”的论点没有说服力,因为有缩小器。

回答by Martin Gottweis

I prefer the var-per-variablenotation:

我更喜欢这样的var-per-variable符号:

var a = 2
var b = 3

because the other comma-instead-of-another-varnotation have these three shortcomings:

因为另一种comma-instead-of-another-var表示法有这三个缺点:

1. Hard to maintain
Consider this code:

1.难以维护
考虑以下代码:

var a = 1,
    b = mogrify(2),
    c = 3

But hey, what does the mogrify do? Let's print b to find out:

但是,嘿,mogrify 是做什么的?让我们打印 b 来找出:

var a = 1,
    b = mogrify(2),
    console.log(b)
    c = 3

breaks stuff

打破东西

2. Hard to read

2.难读

The var in the begging of the line clearly communicates that there will be a new variable initiated.

行乞中的 var 清楚地表明将启动一个新变量。

var get_all_unicorn_promise = db.get_all_unicorns((unicorn) => {
        unicorn.legs.map((leg) => {
            leg.log('yes')
        })
    }).sort(),
    c = 3

What the hell is the c = 3doing there right?

到底在c = 3那里做什么?

3. Not consistent

3. 不一致

Consider this:

考虑一下:

var a = 1,
    b = 2,
    c = 3

With var-per-variableevery declaration follow the same structure. With comma-instead-of-another-varthe first variable is declared in different way than others. If you decide to, say, move the first variable inside a for cycle, you will have to add var to the middle of declarations

随着var-per-variable每一个声明遵循相同的结构。随着comma-instead-of-another-var第一个变量比其他不同的方式申报。如果您决定将第一个变量移到 for 循环内,则必须将 var 添加到声明的中间

Other than preference, it seems like majority of notable projects use the var-per-variablenotation

除了偏好之外,似乎大多数著名项目都使用该var-per-variable符号

回答by Daniel Vassallo

I agree with the other answerers that this is mainly a matter of personal style. But to bring an "Authoritative" opinion into the discussion, this is what Douglas Crockfordsays on the website of the popular JSLint tool:

我同意其他回答者的意见,这主要是个人风格问题。但是为了将“权威”意见带入讨论中,Douglas Crockford在流行的 JSLint 工具网站上是这样说的:

But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be enforced with the onevaroption.

但是因为 JavaScript 没有块作用域,所以在函数顶部声明函数的所有变量是更明智的。建议每个函数使用一个 var 语句。这可以通过onevar选项强制执行。

回答by Heretic Monkey

As others have noted, it is a style preference. JSLintmight tell you to only have one varper function (if you use the "Good Parts"). Thus if using JSLint to check your code (not a bad idea, IMHO), you'll end up using the first format more than the latter.

正如其他人所指出的,这是一种风格偏好。JSLint可能会告诉您var每个函数只有一个(如果您使用“Good Parts”)。因此,如果使用 JSLint 来检查您的代码(不是一个坏主意,恕我直言),您最终会比后者更多地使用第一种格式。

On the other hand, the same author, Douglas Crockford, says to put each variable in its own line in his coding conventions. So you may want to uncheck the "All one varper function" checkbox in JSLint if you use it. ;-)

另一方面,同一位作者Douglas Crockford说在他的编码约定中将每个变量放在自己的行中。因此var,如果您使用 JSLint,您可能希望取消选中“每个函数都一个”复选框。;-)

回答by Scott Mermelstein

Since I don't see any references to it, hereis a link to the ECMA-262 specification, which is the underlying spec for JavaScript. The grammar from that page says:

由于我没有看到任何对它的引用,这里有一个指向 ECMA-262 规范的链接,它是 JavaScript 的底层规范。该页面的语法说:

12.2 Variable Statement

Syntax

  VariableStatement :
    var VariableDeclarationList ;

  VariableDeclarationList :
    VariableDeclaration
    VariableDeclarationList , VariableDeclaration

  VariableDeclarationListNoIn :
    VariableDeclarationNoIn
    VariableDeclarationListNoIn , VariableDeclarationNoIn

  VariableDeclaration :
    Identifier Initialiseropt

  VariableDeclarationNoIn :
    Identifier InitialiserNoInopt

  Initialiser :
    = AssignmentExpression
  InitialiserNoIn :
    = AssignmentExpressionNoIn

What you can glean from this is using commas or not doesn't matter. Either way, it ends up being parsed as a VariableDeclarationand is treated exactly the same. There should be no difference to how the script engine treats the two declarations. The only differences would be ones already mentioned in other answers - saving more space and practically immeasurable differences in the amount of time it takes to apply the grammar to find all the VariableDeclarationswhen the script is compiled.

您可以从中了解到是否使用逗号并不重要。无论哪种方式,它最终都会被解析为 aVariableDeclaration并且被完全相同地对待。脚本引擎处理这两个声明的方式应该没有区别。唯一的区别是其他答案中已经提到的区别 - 节省更多空间,并且在VariableDeclarations编译脚本时应用语法查找所有内容所需的时间量几乎无法估量。

回答by meder omuraliev

I don't think there's any noticeable difference, as far as I'm concerned it's just personal preference.

我不认为有任何明显的差异,就我而言,这只是个人喜好。

I hate having multiple var declarations so I usually do:

我讨厌有多个 var 声明,所以我通常这样做:

var 
   one
  ,two
  ,three
  ,four
;

As it's shorter and arguably more readable, no varnoise to look at.

由于它更短,并且可以说更具可读性,因此没有var噪音。

回答by STW

The first saves a few characters--so there is a very small saving in terms of the JS filesize and therefore bandwidth consumption. The only time this would become noticable would be in extreme cases.

第一个节省了几个字符——因此在 JS 文件大小和带宽消耗方面节省了很小的一部分。只有在极端情况下才会引起注意。

回答by rmeador

I prefer the second version (each has its own var). I think that's because I come from a C++ background. In C++, you can declare variables like you do in your first example, but it is frowned upon (it easily leads to mistakes when you're trying to create pointers that way).

我更喜欢第二个版本(每个版本都有自己的var)。我认为那是因为我来自 C++ 背景。在 C++ 中,您可以像在第一个示例中所做的那样声明变量,但不赞成这样做(当您尝试以这种方式创建指针时很容易导致错误)。

回答by Ryan Kinal

If you are minifying your javascript, there is a fairly large benefit:

如果你正在缩小你的 javascript,有一个相当大的好处:

var one, two, three, four;

becomes

变成

var a, b, c, d;

Where as

然而

var one;
var two;
var three;
var four;

becomes

变成

var a;
var b;
var c;
var d;

That's an additional three instances of var, which can add up over time.

这是 的另外三个实例var,随着时间的推移可以累加。

See The "A List Apart" article series "Better Javascript Minification" Part 1and Part 2

请参阅“A List Apart”系列文章“Better Javascript Minification”第 1部分第 2 部分