简体   繁体   English

JavaScript中的var a =(expression1,expression2)背后的原因是什么?

[英]What is the reason behind var a = (expression1, expression2) in javascript?

Looking through some JS code I have found something like this: 通过查看一些JS代码,我发现了以下内容:

var a, b;
if (  
  (a = someFunction1(), b = someFunction2() )
){
   ...
}

I never found anything like this previously and I do not understand the reason for doing something like this. 我以前从未发现过这样的东西,而且我不明白执行这样的事情的原因。 Therefore I am curious: is the person who has done this out of his mind or am I just not capable to understand his idea. 因此,我很好奇:是做这个事的人还是出于我的理解?

When I try to check what construct like (expression1, expression2) does, I see that it always returns the value of the second expression: 当我尝试检查类似(expression1, expression2) ,我发现它总是返回第二个表达式的值:

(5, 6)   // 6
('strange', 'things')    // 'things'
(4, undefined)     // undefined

So if I would be the one writing this code, I would do something like this: 因此,如果我是编写这段代码的人,我会做这样的事情:

var a = someFunction1(),
    b = someFunction2();

if (b){ ... }

Am I correct in my reasoning? 我的推理正确吗?

When I try to check what construct like (expression1, expression2) does, I see that it always returns the value of the second expression 当我尝试检查类似(expression1, expression2) ,我发现它总是返回第二个表达式的值

Yes. 是。 Even without trying out, this is what the comma operator does. 即使没有尝试,这也是逗号运算符的作用。

Am I correct in my reasoning? 我的推理正确吗?

Yes. 是。 Your code does exactly the same thing, but is more readable. 您的代码执行完全相同的操作,但更具可读性。

You are correct, that is essentially if(b) . 您是正确的,实质上是if(b) The readability of the first version is terrible and does not save on space so it would make no sense for it to be minified like that. 第一个版本的可读性很差,并且不节省空间,因此将其缩小是没有意义的。

Assigning variables inside of conditional statements is bad practice. 在条件语句中分配变量是一种不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM