问题描述
是否有特定的原因我见过许多人写的
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?
推荐答案
这是:
if ("red" === color) {
// ...
}
if (color === "red") {
// ...
}
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:比较运算符中的操作数的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!