问题描述
我一直在编写 if
这样的语句:
Ive been writing my if
statements like this:
if(variable1 === 1){}
if(variable2 > 10){}
if(variable3 == "a"){}
但我记得在某个地方读书(不幸的是我再也找不到那个页面了),如果
语句最好这样写:
But I remember reading somewhere (unfortunately I cant find that page anymore), that if
statements are better off written like this:
if(1 === variable1){}
if(10 < variable2){}
if("a" == variable3){}
你放的地方表达式右侧的变量。
Where you put the variable on the right hand side of the expression.
这是正确的吗?如果是这样,任何人都可以解释为什么这是正确的吗?此外,这适用于所有编程语言,还是只适用于javascript?
Is this correct? And, if so, can anyone shed any light on why this is correct? Also, does this apply to all programming languages, or just javascript?
TIA
推荐答案
1 === variable1
与用Yoda表示法编写的表达式 variable1 === 1
相同**:在左侧列出常数,在右侧列出变量。
1 === variable1
is same as the expression variable1 === 1
written in Yoda notation**: constant listed on left hand side, variable on the right hand side.
一些程序员选择使用它的主要原因是为了避免写入的常见错误 if(a = 1)
程序员实际意味着 if(a == 1)
或 if(a === 1)
。以下代码行将起作用但不是预期的( a
被分配一个值而如果
块将始终被执行):
The main reason why some programmers choose to use it is to avoid the common mistake of writing if (a = 1)
where the programmer actually meant if (a == 1)
or if (a === 1)
. The following line of code will work but not as expected (a
is assigned a value and if
block will always get executed):
if (a = 1) {}
反过来写的相同表达式将生成语法(或编译)错误:
The same expression written the other way round will generate a syntax (or compile) error:
if (1 = a) {}
程序员可以立即发现错误并且修复它。
The programmer can immediately spot the error and fix it.
我不喜欢或使用尤达符号。编码时我试着睁大眼睛。
I do not like or use the Yoda notation. I try to keep my eyes open while coding.
**我无法找到这个词的来源。
** I am unable to find out the origin of this term.
这篇关于if语句中表达式的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!