JavaScript 逗号运算符

发布于 2024-07-13 05:27:41 字数 437 浏览 5 评论 0原文

当将赋值与逗号结合使用时(可能你不应该这样做),javascript如何确定分配哪个值? 考虑这两个片段:

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);

第一个输出

1
4

,第二个输出

4
4

这里的括号有什么作用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

鱼忆七猫命九 2024-07-20 05:27:41

我在这里混淆了两件事。 对“nl”的第一次调用是带有四个参数的函数调用。 第二个是将逗号评估为一个参数。

因此,答案是:以 ',' 分隔的表达式列表的值是 最后一个表达式的值

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文