TypeError: invalid Array.prototype.sort argument

Ngoại lệ JavaScript "invalid Array.prototype.sort argument" xảy ra khi đối số của Array.prototype.sort() (và các phương thức liên quan: Array.prototype.toSorted(), TypedArray.prototype.sort(), TypedArray.prototype.toSorted()) không phải là undefined hoặc một hàm so sánh các toán hạng của nó.

Thông báo

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)

Loại lỗi

TypeError

Nguyên nhân?

Đối số của Array.prototype.sort() (và các phương thức liên quan: Array.prototype.toSorted(), TypedArray.prototype.sort(), TypedArray.prototype.toSorted()) phải là undefined hoặc một hàm so sánh các toán hạng của nó.

Ví dụ

Trường hợp không hợp lệ

js
[1, 3, 2].sort(5); // TypeError
students.toSorted("name"); // TypeError

Trường hợp hợp lệ

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

Xem thêm