简体   繁体   English

JavaScript逗号运算符

[英]Javascript comma operator

When combining assignment with comma (something that you shouldn't do, probably), how does javascript determine which value is assigned? 当将赋值与逗号(可能不应该这样做)结合在一起时,javascript如何确定分配哪个值? Consider these two snippets: 考虑以下两个片段:

function nl(x) { document.write(x + "<br>"); }
var i = 0;
nl(i+=1, i+=1, i+=1, i+=1);
nl(i);

And: 和:

function nl(x) { document.write(x + "<br>"); }
var i = 0;
nl((i+=1, i+=1, i+=1, i+=1));
nl(i);

The first outputs 第一个输出

1
4

while the second outputs 而第二个输出

4
4

What are the parentheses doing here? 括号在这里做什么?

I was confusing two things, here. 我在这里混淆了两件事。 The first call to 'nl' is a function call with four arguments. 对“ nl”的第一个调用是带有四个参数的函数调用。 The second is the evaluation of the comma into one argument. 第二个是将逗号评估为一个参数。

So, the answer: the value of a list of expressions separated by ',' is the value of the last expression . 因此,答案是:用','分隔的表达式列表的值是最后一个表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM