useFind
¥Summary
-
规则生效日期:
v2.3.6¥Rule available since:
v2.3.6 -
诊断类别:
lint/nursery/useFind¥Diagnostic Category:
lint/nursery/useFind -
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 information。
¥The default severity of this rule is information.
-
此规则属于以下域:
¥This rule belongs to the following domains:
-
来源:
¥Sources:
-
与
@typescript-eslint/prefer-find相同¥Same as
@typescript-eslint/prefer-find
-
¥How to configure
{ "linter": { "rules": { "nursery": { "useFind": "error" } } }}¥Description
强制使用 Array.prototype.find() 而不是 Array.prototype.filter() 后跟 [0] 来查找单个结果。
¥Enforce the use of Array.prototype.find() over Array.prototype.filter() followed by [0] when looking for a single result.
在查找数组中符合条件的第一个元素时,可能会想使用类似 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.
¥Examples
¥Invalid
[1, 2, 3].filter(x => x > 1)[0];/invalid.ts:1:1 lint/nursery/useFind ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Prefer using Array#find() over Array#filter[0].
> 1 │ [1, 2, 3].filter(x => x > 1)[0];
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │
ℹ Use Array#find() instead of Array#filter[0] to improve readability.
[1, 2, 3].filter(x => x > 1).at(0);/invalid2.ts:1:1 lint/nursery/useFind ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Prefer using Array#find() over Array#filter[0].
> 1 │ [1, 2, 3].filter(x => x > 1).at(0);
│ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
2 │
ℹ Use Array#find() instead of Array#filter[0] to improve readability.
¥Valid
[1, 2, 3].find(x => x > 1);¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号