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;
}

已知限制

¥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 中引入。

资源