为什么javascript在if语句中接受逗号? [英] Why does javascript accept commas in if statements?

查看:1268
本文介绍了为什么javascript在if语句中接受逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一些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

任何人都知道为什么这是有效的javascript语法?它是否有实际用途?

Anyone know why that is valid javascript syntax? Is there any practical use for it?

推荐答案

逗号运算符将多个表达式链接在一起,操作结果为值最后一个操作数。唯一真正的用途是当您需要多个副作用时,例如分配或函数调用。

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.

这篇关于为什么javascript在if语句中接受逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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