JavaScript 中逗号运算符的作用是什么?
如果我使用:
1.09 * 1; // returns "1.09"
但如果我使用:
1,09 * 1; // returns "9"
我知道 1,09 不是一个数字。
最后一段代码中的逗号有什么作用?
更多示例
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
If I use:
1.09 * 1; // returns "1.09"
But if I use:
1,09 * 1; // returns "9"
I know that 1,09 isn't a number.
What does the comma do in the last piece of code?
More Examples
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来源 https://developer.mozilla。 org/en/JavaScript/Reference/Operators/Special_Operators/Comma_Operator
例如,表达式
1,2,3,4,5
的计算结果为5
。显然,逗号运算符仅对有副作用的操作有用。Source: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special_Operators/Comma_Operator
For example, the expression
1,2,3,4,5
evaluates to5
. Obviously the comma operator is useful only for operations with side-effects.还有一些需要考虑的:
Some more to consider:
特定的语法允许面包店功能性地烘烤面包,将其交给顾客食用,并将
返回
的数量保持为零。所有这些都利用括号内的箭头函数。The specific syntax allows a bakery to functionally bake bread, hand it to the customer for consumption and also keep the number of
return
s to zero. All these by utilizing parenthesized arrow functions.向对象添加/修改属性并在同一行中返回它是一种可能的用例:
上面的匿名函数返回一个对象,其随机值大于输入值,或者,如果没有,则输入值本身位于
bigger
属性中包含的数组中。它仍然是语法糖(例如 箭头函数),但它确实缩短了行数...我想知道是否有一些 JS 压缩器会自动以类似的方式检测和调整代码。在控制台中运行它:
Adding/modifying properties to an object and returning it in the same line is a possible use-case:
The above anonymous function returns an object with random values bigger than the input value or, if there's none, with the input value itself in an array in contained in the
bigger
property.It is still syntactic sugar (like arrow functions), but it does shorten the number of lines... I wonder if some JS minifiers detect and adjust the code in a similar way automatically. Run it in your console:
看看这里 - 逗号代表多个表达式 /声明。例如,在您的代码中,您可以使用如下行:
这将声明所有三个变量,而无需编写:
希望有帮助。
Have a look here - the comma stands for multiple expressions / statements. For example in your code you could use a line like this:
This would declare all three variables without writing:
Hope that helps.