Skip to content
← Back to rules

unicorn/prefer-array-find 性能

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

它的作用

建议使用 Array.prototype.findArray.prototype.findLast,而不是从 filter(...) 的结果中获取第一个或最后一个匹配元素。

为什么这不好?

使用 filter(...)[0] 或数组解构来获取第一个匹配项,相比使用 find(...) 效率更低且更加冗长。找到匹配项后,findfindLast 会提前结束查找,而 filter 则会遍历整个数组。

示例

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

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

const match = users.filter(fn).at(-1);
const match = users.filter(fn).pop();

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

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

const match = users.findLast(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 中添加。

参考资料