Javascript comma operator

∥☆過路亽.° 提交于 2019-12-13 20:44:54

问题


When combining assignment with comma (something that you shouldn't do, probably), how does javascript determine which value is assigned? 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?


回答1:


I was confusing two things, here. The first call to 'nl' is a function call with four arguments. 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.



来源:https://stackoverflow.com/questions/502138/javascript-comma-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!