TypeError: invalid Array.prototype.sort argument
JavaScript 异常“Array.prototype.sort 参数无效”发生在当 Array.prototype.sort()(及其相关方法:Array.prototype.toSorted()、TypedArray.prototype.sort()、TypedArray.prototype.toSorted())的参数既不是 undefined 也不是一个比较其操作数的函数时。
消息
TypeError: The comparison function must be either a function or undefined (V8-based) TypeError: invalid Array.prototype.sort argument (Firefox) TypeError: non-function passed to Array.prototype.toSorted (Firefox) TypeError: invalid %TypedArray%.prototype.sort argument (Firefox) TypeError: Array.prototype.sort requires the comparator argument to be a function or undefined (Safari) TypeError: Array.prototype.toSorted requires the comparator argument to be a function or undefined (Safari) TypeError: TypedArray.prototype.sort requires the comparator argument to be a function or undefined (Safari) TypeError: TypedArray.prototype.toSorted requires the comparator argument to be a function or undefined (Safari)
错误类型
TypeError
哪里出错了?
Array.prototype.sort()(及其相关方法:Array.prototype.toSorted()、TypedArray.prototype.sort()、TypedArray.prototype.toSorted())的参数应为 undefined 或一个比较其操作数的函数。
示例
无效案例
js
[1, 3, 2].sort(5); // TypeError
students.toSorted("name"); // TypeError
有效情况
js
[1, 3, 2].sort(); // [1, 2, 3]
[1, 3, 2].sort((a, b) => a - b); // [1, 2, 3]
students.toSorted((a, b) => a.name.localeCompare(b.name));