带有括号和逗号的变量分配不熟悉 [英] Unfamiliar variable assignment with parenthesis and commas

查看:37
本文介绍了带有括号和逗号的变量分配不熟悉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样分配带有括号的值只会求出最后一个值

Why does assigning values with parenthesis like this only evaluate to the last value

 var a = (1, 2, 5 - 1); //4

它似乎也需要括号

var a = 1, 5 - 1; //SyntaxError: Unexpected number

推荐答案

符号在JavaScript语法中具有几个相似但明显不同的角色.在 var 声明中,逗号分隔变量声明子句.但是,在表达式中,逗号运算符"提供了一种以语法上等效于单个表达式的形式将多个表达式填充在一起的方法.在某些罕见的情况下,这很有用.

The , symbol has several similar but distinctly different roles in JavaScript syntax. In a var declaration, the comma separates variable declaration clauses. In an expression, however, the comma "operator" provides a way to stuff several expressions together in a form that is syntactically equivalent to a single expression. That's somewhat useful in certain rare cases.

因此,括号在这里有所不同,因为没有它们,解析器希望每个逗号分隔的子句都是变量声明和(可选)初始化.用括号括起来,在语法上,初始化的右侧是单个表达式,即使它是由逗号运算符连接的三个独立的不相关表达式.

Thus, the parentheses make a difference here because without them, the parser expects each comma-separated clause to be a variable declaration and (optional) initialization. With the parentheses, the right-hand side of the initialization is a single expression, syntactically, even though it's three separate unrelated expressions connected by the comma operator.

当存在涉及允许单个表达式的语法的情况时,表达式中的逗号运算符无疑是有用的,但是您确实要使用多个表达式.最好的例子是 for 循环头中的第三子句.如果需要增加两个单独的变量,则在循环头中这样做可能会更清楚;但是,仅提供一种表达方式.因此,逗号运算符可让您作弊:

The comma operator in expressions is arguably useful when there's a situation that involves syntax that allows for a single expression, but you really want to use more than one. The best example is the third clause in a for loop header. If you need to increment two separate variables, then it (may) be clearer to do that in the loop header; however, there's only provision for one expression. Thus the comma operator lets you cheat:

for (var a = 0, b = 1; a < limit; a++, b = something(b)) {
  // ...
}

请注意, for 标头的 first 子句中的逗号是 not 逗号运算符;这是逗号分隔变量声明子句.(我想有些人可能仍会使用逗号运算符"一词,但我的意思是,它不是分隔表达式的列表.)

Note that the comma in the first clause of the for header is not the comma operator; it's the comma that separates variable declaration clauses. (I guess some people might still use the term "comma operator" for that, but my point is that it's not separating a list of expressions.)

这篇关于带有括号和逗号的变量分配不熟悉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆