Skip to content
← Back to rules

unicorn/consistent-existence-index-check Style

🛠️ 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) {
}

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "rules": {
    "unicorn/consistent-existence-index-check": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/consistent-existence-index-check": "error",
  },
});
bash
oxlint --deny unicorn/consistent-existence-index-check

版本

此规则于 v0.12.0 中添加。

参考资料