Skip to content
← Back to rules

unicorn/prefer-includes Style

💡 A suggestion is available for this rule.

它的作用

在检查是否存在或不存在时,优先使用 includes() 而不是 indexOf()。 所有内置对象除了 .indexOf() 之外,也都有 .includes()

为什么这不好?

.indexOf() 相比,.includes() 方法更易读,也更不容易出错。

示例

以下是此规则的错误代码示例:

javascript
if (str.indexOf("foo") !== -1) {
}

以下是此规则的正确代码示例:

javascript
if (str.includes("foo")) {
}

如何使用

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

json
{
  "rules": {
    "unicorn/prefer-includes": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  rules: {
    "unicorn/prefer-includes": "error",
  },
});
bash
oxlint --deny unicorn/prefer-includes

版本

此规则于 v0.0.18 中添加。

参考资料