逗号运算符返回参数列表中的第一个值而不是第二个值?
MDN claims that:
The comma operator evaluates both of its operands (from left to right)
and returns the value of the second operand.
However, when I tried running <script> alert(1, 2); </script>
, it shows a "1" instead of a "2".
Am I misunderstanding something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在函数调用的上下文中,逗号用于将参数彼此分隔。因此,您要做的就是将第二个参数传递给
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:
The extra brackets form a parameter on their own; inside them you can use the comma as an operator.
逗号
(,)
也是一个参数分隔符。请改用
alert((1,2))
。Comma
(,)
is also a parameter separator.Use
alert((1,2))
instead.当您这样使用它时,逗号不是一个运算符,它是调用
alert
方法时参数之间的分隔符。如果您将它们放在括号中以使其成为一个表达式,它将显示
2
:When you use it like that, the comma is not an operator, it's a separator between the parameters in the call to the
alert
method.If you put parentheses around them so that it's an expression, it will show you
2
: