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));