javascript 为什么javascript在if语句中接受逗号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5347995/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:54:04  来源:igfitidea点击:

Why does javascript accept commas in if statements?

javascriptparsinglogic

提问by Matt

I stumbled across some javascript syntax that seemed like it should produce a parse error of some kind but doesn't:

我偶然发现了一些 javascript 语法,它们似乎应该会产生某种解析错误,但不会:

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?

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

采纳答案by Ignacio Vazquez-Abrams

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.

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

回答by Matt Briggs

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

javascript 中的逗号实际上非常神秘。我见过的最酷的用法是这个

while(doSomething(), checkIfSomethingHappened());

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

最常见的是 var 在现代 js 中的使用方式

var foo = 1,
    bar = 2;

回答by Suroot

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++) {
....
}

回答by vinyll

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

我允许在相同的上下文中进行操作和比较。

Example:

例子:

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