useArraySortCompare
¥Summary
-
规则生效日期:
v2.3.5¥Rule available since:
v2.3.5 -
诊断类别:
lint/nursery/useArraySortCompare¥Diagnostic Category:
lint/nursery/useArraySortCompare -
此规则没有修复方案。
¥This rule doesn’t have a fix.
-
此规则的默认严重级别为 information。
¥The default severity of this rule is information.
-
此规则属于以下域:
¥This rule belongs to the following domains:
-
来源:
¥Sources:
¥How to configure
{ "linter": { "rules": { "nursery": { "useArraySortCompare": "error" } } }}¥Description
要求 Array#sort 和 Array#toSorted 调用始终提供 compareFunction。
¥Require Array#sort and Array#toSorted calls to always provide a compareFunction.
当未使用比较函数调用 Array#sort() 和 Array#toSorted() 时,它们会将所有非 undefined 数组元素转换为字符串,然后基于它们的 UTF-16 代码单元 ECMA 规范 对这些字符串进行比较。
¥When called without a compare function, Array#sort() and Array#toSorted() converts all non-undefined array elements into strings and then compares said strings based off their UTF-16 code units ECMA specification.
结果是元素按字母顺序排序,无论其类型如何。例如,对数字进行排序时,会得到 “10 之前 2” 顺序:
¥The result is that elements are sorted alphabetically, regardless of their type. For example, when sorting numbers, this results in a “10 before 2” order:
[1, 2, 3, 10, 20, 30].sort(); //→ [1, 10, 2, 20, 3, 30]此规则会报告任何未提供比较参数的排序方法调用。
¥This rule reports on any call to the sort methods that do not provide a compare argument.
¥Examples
¥Invalid
const array: any[] = [];array.sort();/invalid.ts:2:1 lint/nursery/useArraySortCompare ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
ℹ Compare function missing.
1 │ const array: any[] = [];
> 2 │ array.sort();
│ ^^^^^^^^^^^^
3 │
ℹ When called without a compare function, Array#sort() and Array#toSorted() converts all non-undefined array elements into strings and then compares said strings based off their UTF-16 code units.
ℹ Add a compare function to prevent unexpected sorting.
¥Valid
const array: any[] = [];array.sort((a, b) => a - b);¥Related links
Biome v2.1 中文网 - 粤ICP备13048890号