逗号运算符在参数列表中返回第一个值而不是第二个值? [英] Comma operator returns first value instead of second in argument list?

查看:98
本文介绍了逗号运算符在参数列表中返回第一个值而不是第二个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MDN 声称:


逗号运算符计算其两个操作数(从左到右)
返回第二个操作数的值

但是,当我尝试运行<脚本>警报(1,2); < / script> ,它显示1而不是2。

However, when I tried running <script> alert(1, 2); </script>, it shows a "1" instead of a "2".

我误解了什么吗?

推荐答案

在函数调用的上下文中,逗号用于将参数彼此分开。所以你要做的就是将第二个参数传递给 alert(),这会被忽略。

In the context of a function call, the comma is used to separate parameters from each other. So what you're doing is passing a second parameter to alert() which gets silently ignored.

你是什么希望是这样的:

What you want is possible this way:

 alert((1,2));

额外的括号自行构成一个参数;在它们内部,您可以使用逗号作为运算符。

The extra brackets form a parameter on their own; inside them you can use the comma as an operator.

这篇关于逗号运算符在参数列表中返回第一个值而不是第二个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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