“value == var”与“var == value”相对 [英] "value == var" versus "var == value"
问题描述
在很多地方,我看到开发人员正在进行 value == var
比较,如下所示:
At many places, I've seen developers doing value == var
comparisons, like this:
if ('https' === location.protocol) {
port = 8443;
protocol = 'wss://';
isSecure = true;
}
我知道 a == b
与 b == a
相同,那么为什么人们使用 value == var
而不是 var == value
?
I know that a == b
is same as b == a
, so why do people use value == var
instead of var == value
?
这是否有标准?如果是,那是标准方式?
Is there a standard for this? And if yes, which is the standard way?
推荐答案
您所看到的是 yoda条件。
尤达条件描述的是相同的表达式,但是相反:
Yoda conditions describe the same expression, but reversed:
if ( 42 == $value ) { /* ... */ }
// Reads like: "If 42 equals the value..."
优点是
在表达式中放置常量值不会改变程序的行为(除非值计算为false - 见下文)。在使用单个等号(=)进行赋值而不进行比较的编程语言中,可能的错误是无意中分配值而不是编写条件语句。
Placing the constant value in the expression does not change the behavior of the program (unless the values evaluate to false—see below). In programming languages that use a single equals sign (=) for assignment and not for comparison, a possible mistake is to assign a value unintentionally instead of writing a conditional statement.
请注意,它显然缺乏可读性。我个人不喜欢这种方式。
Note that it is clearly lack of readability. I personally don't prefer this way.
这篇关于“value == var”与“var == value”相对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!