JavaScript 表达式中的逗号有什么作用?
如果我使用:
1.09 * 1; // returns "1.09"
但如果我使用:
1,09 * 1; // returns "9"
我知道 1,09 不是数字.
I know that 1,09 isn't a number.
最后一段代码中的逗号有什么作用?
What does the comma do in the last piece of code?
if (0,9) alert("ok"); // alert
if (9,0) alert("ok"); // don't alert
<小时>
alert(1); alert(2); alert(3); // 3 alerts
alert(1), alert(2), alert(3); // 3 alerts too
<小时>
alert("2",
foo = function (param) {
alert(param)
},
foo('1')
)
foo('3'); // alerts 1, 2 and 3
推荐答案
逗号运算符同时计算它的操作数(从左到右)和返回第二个的值操作数.
The comma operator evaluates both of its operands (from left to right) and returns the value of the second operand.
来源: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Comma_Operator
例如,表达式 1,2,3,4,5
的计算结果为 5
.显然,逗号操作符只对有副作用的操作有用.
For example, the expression 1,2,3,4,5
evaluates to 5
. Obviously the comma operator is useful only for operations with side-effects.
console.log(1,2,3,4,5);
console.log((1,2,3,4,5));
相关文章