我最近读了一段JavaScript代码,看到了这行:
var myVar = (12,5); // myVar==5 now
这个
(x, y)
的语法是什么意思?我最近读了一段JavaScript代码,看到了这行:
var myVar = (12,5); // myVar==5 now
(x, y)
的语法是什么意思?逗号运算符
,
具有从左到右的结合性
。由逗号分隔的两个表达式从左到右进行评估。左操作数始终被评估,所有副作用都在评估右操作数之前完成。
表达式:
var myVar = (12, 5);
等同于:
var myVar = 5;
=
优先级高于,
,否则如果没有括号,像var myVar = 12, 5
这样的表达式等同于var myVar = 12
。When first expression has some side-effects:
var myVar = ( expression1, expression2);
The expression1
may have some side effects that may required before to assign the result of expression2
to myVar
, e.g. var mayVar = (++i, i + j);
In this expression incremented value after ++i
will be added with j
and result will be assigned to mayVar
.
Bug fixed or bug:
May be some bug fixing/or during testing instead of assigning x
developer wanted to assign y
but forgot to remove (
)
before public relies.
var myVar = (x, y);
I also find a typo-bug in which questioner forgot to write function same and instead of writing
var myVar = fun(x, y);
his typo:
var myVar = (x, y);
In the linked question.
这不是关于JavaScript的链接,而是一个涉及合法/可能使用逗号运算符的有趣的C++链接 逗号运算符的正确使用方式是什么?
这被称为逗号运算符。
逗号运算符从左到右评估其两个操作数,并返回第二个操作数的值。
以下是一些示例:
var a = (12,3) //a =3;
var b = (a+2, 2) //a=5, b= 2
var c = (a,b) // a= 5, b=2, c=2.
let a = 1, b = 2, c = 3; for(let i = 0, j = 10; i < j; i++, j--){ // do something } let d = (5 + 3, 7 - 2); // d的值为5
- Yoshi