no-self-compare
禁止双方完全相同的比较
将一个变量与自身进行比较通常是一个错误,要么是打字错误,要么是重构错误。这会让读者感到困惑,并可能引入运行时错误。
🌐 Comparing a variable against itself is usually an error, either a typo or refactoring error. It is confusing to the reader and may potentially introduce a runtime error.
你唯一会将一个变量与自身比较的情况是当你测试 NaN 时。然而,对于这种用例,更合适的做法是使用 typeof x === 'number' && isNaN(x) 或 Number.isNaN ES2015 函数,而不是让代码的读者去判断自我比较的意图。
🌐 The only time you would compare a variable against itself is when you are testing for NaN. However, it is far more appropriate to use typeof x === 'number' && isNaN(x) or the Number.isNaN ES2015 function for that use case rather than leaving the reader of the code to determine the intent of self comparison.
规则详情
🌐 Rule Details
引发此错误是为了高亮一段可能令人困惑且可能毫无意义的代码。几乎没有情况需要将某个东西与其自身进行比较。
🌐 This error is raised to highlight a potentially confusing and potentially pointless piece of code. There are almost no situations in which you would need to compare something to itself.
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-self-compare: "error"*/
let x = 10;
if (x === x) {
x = 20;
}
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
已知限制
🌐 Known Limitations
这个规则的工作原理是直接比较运算符两边的标记。如果它们在结构上相同,则将其标记为有问题。然而,它并未考虑可能的副作用,或者函数即使在使用相同参数调用时也可能返回不同的对象。因此,在某些情况下,它可能会产生误报,例如:
🌐 This rule works by directly comparing the tokens on both sides of the operator. It flags them as problematic if they are structurally identical. However, it doesn’t consider possible side effects or that functions may return different objects even when called with the same arguments. As a result, it can produce false positives in some cases, such as:
/*eslint no-self-compare: "error"*/
function parseDate(dateStr) {
return new Date(dateStr);
}
if (parseDate('December 17, 1995 03:24:00') === parseDate('December 17, 1995 03:24:00')) {
// do something
}
let counter = 0;
function incrementUnlessReachedMaximum() {
return Math.min(counter += 1, 10);
}
if (incrementUnlessReachedMaximum() === incrementUnlessReachedMaximum()) {
// ...
}
版本
此规则是在 ESLint v0.0.9 中引入。