Skip to main content

require-array-sort-compare

Require Array#sort and Array#toSorted calls to always provide a compareFunction.

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

当不带比较函数调用时,Array#sort()Array#toSorted() 会将所有非未定义数组元素转换为字符串,然后根据它们的 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]

此规则报告对标记为 compare 的代码的任何引用。

¥This rule reports on any call to the sort methods that do not provide a compare argument.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/require-array-sort-compare": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

此规则旨在确保所有原生排序方法的调用都提供 compareFunction,同时忽略对用户定义方法的调用。

¥This rule aims to ensure all calls of the native sort methods provide a compareFunction, while ignoring calls to user-defined methods.

const array: any[];
const stringArray: string[];

array.sort();

// String arrays should be sorted using `String#localeCompare`.
stringArray.sort();
Open in Playground

选项

该规则接受以下选项:

type Options = [
{
/** Whether to ignore arrays in which all elements are strings. */
ignoreStringArrays?: boolean;
},
];

const defaultOptions: Options = [{ ignoreStringArrays: true }];

¥Options

ignoreStringArrays

Whether to ignore arrays in which all elements are strings. Default: true.

带有 { ignoreStringArrays: true } 的此规则的代码示例:

¥Examples of code for this rule with { ignoreStringArrays: true }:

const one = 1;
const two = 2;
const three = 3;
[one, two, three].sort();
Open in Playground

何时不使用它

¥When Not To Use It

如果你有意希望数组始终以类似字符串的方式排序,则可以安全地关闭此规则。

¥If you intentionally want your arrays to be always sorted in a string-like manner, you can turn this rule off safely.


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.

'## 资源'