Skip to content
← Back to rules

unicorn/prefer-array-find Perf

🚧 An auto-fix is planned for this rule, but not implemented at this time.

它的作用

鼓励在只需要第一个匹配元素时,使用 Array.prototype.find,而不是 filter(...)[0] 或 类似的模式。

为什么这不好?

使用 filter(...)[0] 来获取第一个匹配项,不如使用 find(...) 高效,也更冗长。 find 在找到匹配项时会提前结束,而 filter 会遍历整个数组。

示例

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

js
const match = users.filter((u) => u.id === id)[0];
const match = users.filter(fn).shift();

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

js
const match = users.find((u) => u.id === id);
const match = users.find(fn);

如何使用

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

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

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

版本

此规则已在 v0.16.12 中添加。

参考资料