开发者

Comma operator returns first value instead of second in argument list?

开发者 https://www.devze.com 2023-02-23 06:29 出处:网络
MDN claims that: The comma operator evaluates 开发者_StackOverflowboth of its operands (from left to right)

MDN claims that:

The comma operator evaluates 开发者_StackOverflowboth 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?


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.


Comma(,) is also a parameter separator.

Use alert((1,2)) instead.


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:

alert( (1,2) );
0

精彩评论

暂无评论...
验证码 换一张
取 消