Skip to content
← Back to rules

unicorn/consistent-existence-index-check 风格

An auto-fix is available for this rule.

它的作用

强制对使用 indexOf()lastIndexOf()findIndex() 以及 findLastIndex() 进行元素存在性检查时采用一致的风格。这确保了比较操作以标准且清晰的方式进行。

为什么这是个问题?

该规则旨在强制执行特定的代码风格,以提高代码清晰度。使用不一致的比较风格(例如 index < 0index >= 0)会使代码意图变得模糊,尤其是在大型代码库中尤为明显。

示例

以下为 错误 的代码示例:

javascript
const index = foo.indexOf("bar");
if (index < 0) {
}

const index = foo.indexOf("bar");
if (index >= 0) {
}

以下为 正确 的代码示例:

javascript
const index = foo.indexOf("bar");
if (index === -1) {
}

const index = foo.indexOf("bar");
if (index !== -1) {
}

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "unicorn/consistent-existence-index-check": "error"
  }
}
bash
oxlint --deny unicorn/consistent-existence-index-check

参考资料