prefer-find
Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/stylistic-type-checked"
可启用此规则。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
在数组中搜 索符合条件的第一个项目时,可能很容易使用像 arr.filter(x => x > 0)[0]
这样的代码。但是,使用 Array.prototype.find() 代替 arr.find(x => x > 0)
更简单,它也会返回第一个符合条件的条目。因为 .find()
只需要执行回调直到找到匹配项,所以它也更有效率。
¥When searching for the first item in an array matching a condition, it may be tempting to use code like arr.filter(x => x > 0)[0]
.
However, it is simpler to use Array.prototype.find() instead, arr.find(x => x > 0)
, which also returns the first entry matching a condition.
Because the .find()
only needs to execute the callback until it finds a match, it's also more efficient.
请注意方法之间短路行为的差异。.find()
将仅在找到匹配项之前对数组元素执行回调,而 .filter()
则对所有数组元素执行回调。因此,在修复此规则的错误时,请确保你的 .filter()
回调没有副作用。
¥Beware the difference in short-circuiting behavior between the approaches.
.find()
will only execute the callback on array elements until it finds a match, whereas .filter()
executes the callback for all array elements.
Therefore, when fixing errors from this rule, be sure that your .filter()
callbacks do not have side effects.
- ❌ Incorrect
- ✅ Correct
[1, 2, 3].filter(x => x > 1)[0];
[1, 2, 3].filter(x => x > 1).at(0);
Open in Playground[1, 2, 3].find(x => x > 1);
Open in Playground- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-find": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/prefer-find": "error"
}
};
在线运行试试这个规则 ↗
选项
该规则不可配置。
何时不使用它
¥When Not To Use It
如果你有意使用像 .filter(callback)[0]
这样的模式在所有数组元素上执行 callback
中的副作用,你将需要避免此规则。
¥If you intentionally use patterns like .filter(callback)[0]
to execute side effects in callback
on all array elements, you will want to avoid this rule.
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.
'## 资源'