简体   繁体   English

可以大于比较返回除true或false之外的任何内容吗?

[英]Can greater than comparison return anything other than true or false?

I found the following in a code example at datatables.net. 我在datatables.net的代码示例中找到了以下内容。

return value > 20 ? true : false;

Why wouldn't they have just written 他们为什么不写完

return value > 20;

Could the latter return values other than true or false? 后者可以返回除true或false之外的值吗? Trying to figure out whether they were maybe just thinking the code was more readable this way, or whether there is actually a significant reason for doing this that I'm not aware of. 试图弄清楚他们是否只是认为代码在这种方式下更具可读性,或者是否实际上有一个重要原因,我不知道这样做。

This is along the same lines as someone writing this: 这和写这篇文章的人一样:

if(value > 20 === true){ . . . }

Which is unnecessary because if conditions are implicitly compared against their "truthy-ness". 这是不必要的,因为if条件被隐含地与他们的“真实性”进行比较。 The statement should be: 声明应该是:

if(value > 20){ . . . }

As such, in your example, the code should just be: 因此,在您的示例中,代码应该只是:

return value > 20;

Because (as you correctly surmize) a greater-than/less-than expression can only result in true or false . 因为(正确地猜测)大于/小于表达式只会导致truefalse

Now, if someone wanted to return an alternate set of binary results, then you could see something like this being used: 现在,如果有人想要返回另一组二进制结果,那么你可以看到这样的东西被使用:

return value > 20 ? "acceptable" : "unacceptable";

The only possible result is true or false. 唯一可能的结果是真或假。 I don't think it makes it more readable. 我认为它不会让它更具可读性。 The only reason they may have done it that I can think of is that they were a new developer and didn't realize value > 20 was valid to return. 他们可能想到的唯一原因就是他们是一个新的开发人员并没有意识到价值> 20是有效的回报。

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

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