javascript 比较三个整数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7813366/
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
Comparing three integer values
提问by user979431
Is something like this ever possible?
这样的事情有可能吗?
if(a == b == c)
or is
或者是
if((a== b) && (b == c))
is the only way?
是唯一的方法吗?
or what is the coolest way to do that?
或者最酷的方法是什么?
回答by Mark Byers
In some languages you canuse that shorthand. For example in Python a == b == c
is roughly equivalent to the expression a == b and b == c
, except that b is only evaluated once.
在某些语言中,您可以使用该速记。例如,在 Pythona == b == c
中大致相当于表达式a == b and b == c
,只是 b 只计算一次。
However in Java and Javascript you can'tuse the short version - you have to write it as in the second example. The first example would be approximately equivalent to the following:
但是,在 Java 和 Javascript 中,您不能使用简短版本 - 您必须像第二个示例中那样编写它。第一个示例大致等效于以下内容:
boolean temp = (a == b);
if (temp == c) {
// ...
}
This is not what you want. In Java a == b == c
won't even compile unless c
is a boolean.
这不是你想要的。在 Java 中,a == b == c
除非c
是布尔值,否则甚至不会编译。
回答by java_mouse
In java - we don't have the == shortcut operator. so we end up doing individual equalities.
在 Java 中 - 我们没有 == 快捷操作符。所以我们最终做到了个人平等。
But If you think you will need functionality a lot with varyingnumber of arguments, I would consider implementing a function like this. The following is the sample code without handling exceptional conditions.
但是,如果您认为您需要具有不同数量参数的功能,我会考虑实现这样的功能。以下是不处理异常情况的示例代码。
public static boolean areTheyEqual(int... a) {
int VALUE = a[0];
for(int i: a) {
if(i!= VALUE)
return false;
}
return true;
}
回答by namuol
In JavaScript, your safest bet is a === b && b === c
. I always avoid using ==
in favor of ===
for my own sanity. Here's a more detailed explanation.
在 JavaScript 中,最安全的选择是a === b && b === c
. 我总是避免使用==
有利于===
我自己的理智。这里有更详细的解释。
回答by ezvine
In Scala you can use tuples for this:
在 Scala 中,您可以为此使用元组:
(a, b) == (c, c)
(a, b) == (c, c)
This will check a == c
and b == c
, i.e same as a == b == c
这将检查a == c
和b == c
,即与a == b == c
回答by vBelt
To get the max value out of three numbers, one line method:
要从三个数字中获取最大值,一行方法:
int max = (a > b && a > c) ? a : ((b > a && b > c) ? b : c);
int max = (a > b && a > c) ? a : ((b > a && b > c) ? b : c);