为什么 javascript 在 if 语句中接受逗号?
我偶然发现了一些 javascript 语法,它似乎应该产生某种解析错误,但实际上并没有:
if (true, true) {console.log('splendid')} else {console.log('horrid')} // splendid
if (true, false) {console.log('splendid')} else {console.log('horrid')} // horrid
似乎只有最后一个表达式会影响逻辑,尽管所有表达式都会被执行:
if (console.log('super'), true) {console.log('splendid')} // super splendid
有人知道为什么这是有效的 javascript 语法吗?它有什么实际用途吗?
I stumbled across some javascript syntax that seemed like it should produce a parse error of some kind but doesn't:
if (true, true) {console.log('splendid')} else {console.log('horrid')} // splendid
if (true, false) {console.log('splendid')} else {console.log('horrid')} // horrid
It seems only the last expression affects the logic, though all expressions are executed:
if (console.log('super'), true) {console.log('splendid')} // super splendid
Anyone know why that is valid javascript syntax? Is there any practical use for it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
逗号运算符将多个表达式链接在一起,运算结果是最后一个操作数的值。它唯一真正的用处是当您需要发生多种副作用时,例如赋值或函数调用。
The comma operator chains multiple expressions together, and the result of the operation is the value of the last operand. The only real use for it is when you need multiple side effects to occur, such as assignment or function calls.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators /Special_Operators/Comma_Operator
https://developer.mozilla.org/en /Core_JavaScript_1.5_Guide/Expressions_and_Operators#comma_operator
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Comma_Operator
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Expressions_and_Operators#comma_operator
JavaScript 中的逗号实际上非常晦涩难懂。我见过的最酷的用法是,
最常见的是现代 js 中使用 var 的方式
commas in javascript are actually pretty arcane. The coolest use I have seen is this
the most common would be the way var is used in modern js
这也与大多数其他编程语言相同,在这些编程语言中,循环中可能有多个迭代器。
This is also the same as in most other programming languages where you might have multiple iterators in a loop.
我允许在相同的上下文中进行运算和比较。
例子:
I permits to do operations and comparisons in the same context.
Example: