为什么 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 语法吗? 它有什么实际用途吗?

26992 次浏览

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.

commas in javascript are actually pretty arcane. The coolest use I have seen is this

while(doSomething(), checkIfSomethingHappened());

the most common would be the way var is used in modern js

var foo = 1,
bar = 2;

This is also the same as in most other programming languages where you might have multiple iterators in a loop.

int x,y;
for(x = 0, y = 0; x < 10 || y < 100; x++, y++) {
....
}

I permits to do operations and comparisons in the same context.

Example:

if(a = 2, a > 1) console.log('a is', a)