Javascript:比较运算符中的操作数的顺序 [英] Javascript: Order of operands in comparison operator

查看:161
本文介绍了Javascript:比较运算符中的操作数的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有特定的原因我见过许多人写的

Is there a specific reason why I have seen many people writing

if(1 === a) {...}

而不是

if(a === 1) {...}

给出了一个答案,其中我写了一些像 Array === obj.constructor 这是当有人问我他经常看到人写这样而不是 obj.constructor === Array

I had given an answer in which I wrote something like Array === obj.constructor which is when someone asked me that he has often seen people writing like this instead of obj.constructor === Array.

所以我用哪种方式真的很重要。

So does it really matter which way I use?

推荐答案

这是 yoda条件


Yoda条件是这样命名的,因为条件的文字值先出现,而变量出现在第二。例如,以下是Yoda条件:

Yoda conditions are so named because the literal value of the condition comes first while the variable comes second. For example, the following is a Yoda condition:



if ("red" === color) {
    // ...
}




这被称为尤达条件,因为它读作,红色是颜色,类似于星球大战字符尤佳说话的方式。与安排操作数的其他方式比较:

This is called a Yoda condition because it reads as, "red is the color", similar to the way the Star Wars character Yoda speaks. Compare to the other way of arranging the operands:



if (color === "red") {
    // ...
}




这通常表示颜色是红色,这可能是一种更自然的方式来描述比较。

This typically reads, "color is red", which is arguably a more natural way to describe the comparison.

Yoda条件的支持者强调,错误地使用=而不是==,因为你不能分配一个文字值。这样做会导致语法错误,并会在早期被通知错误。因此,这种做法在早期编程中非常常见,因为工具尚不可用。

Proponents of Yoda conditions highlight that it is impossible to mistakenly use = instead of == because you cannot assign to a literal value. Doing so will cause a syntax error and you will be informed of the mistake early on. This practice was therefore very common in early programming where tools were not yet available.

Yoda条件的反对者指出,工具使我们更好的程序员,因为工具会捕获错误使用=而不是==(ESLint会抓住这个你)。因此,他们认为,模式的效用并不超过代码在使用Yoda条件时的可读性。

Opponents of Yoda conditions point out that tooling has made us better programmers because tools will catch the mistaken use of = instead of == (ESLint will catch this for you). Therefore, they argue, the utility of the pattern doesn’t outweigh the readability hit the code takes while using Yoda conditions.

这篇关于Javascript:比较运算符中的操作数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆