HTML: Markup language
CSS: Styling language
JavaScript: Scripting language
Web APIs: Programming interfaces
All web technology
Learn web development
Discover our tools
Get to know MDN better
此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
View in English Always switch to English
JavaScript 异常“invalid Array.prototype.sort argument”会在 Array.prototype.sort() 方法(以及其相关方法:Array.prototype.toSorted()、TypedArray.prototype.sort()、TypedArray.prototype.toSorted())的参数既不是 undefined 也不是用于比较其操作数的函数时触发。
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) 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 或用于比较其操作数的函数。
[1, 3, 2].sort(5); // TypeError students.toSorted("name"); // TypeError
[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));