JavaScript 表达式中的逗号有什么作用? [英] What does a comma do in JavaScript expressions?

查看:21
本文介绍了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));

这篇关于JavaScript 表达式中的逗号有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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