Skip to main content

require-array-sort-compare

Require Array#sort calls to always provide a compareFunction.

💭

该规则需要 类型信息 才能运行。


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 规范].

英: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.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/require-array-sort-compare": "error"
}
};
在线运行试试这个规则 ↗

示例

此规则旨在确保对原生排序方法的所有调用都提供 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

选项

ignoreStringArrays

此规则与 { 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

何时不使用它

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

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

选项

该规则接受以下选项

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

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

资源