Thanks to visit codestin.com
Credit goes to developer.mozilla.org

Dieser Inhalt wurde automatisch aus dem Englischen übersetzt, und kann Fehler enthalten. Erfahre mehr über dieses Experiment.

View in English Always switch to English

TypeError: ungültiges Array.prototype.sort Argument

Der JavaScript-Ausnahmefehler "ungültiges Array.prototype.sort Argument" tritt auf, wenn das Argument von Array.prototype.sort() (und seine verwandten Methoden: Array.prototype.toSorted(), TypedArray.prototype.sort(), TypedArray.prototype.toSorted()) weder undefined noch eine Funktion ist, die ihre Operanden vergleicht.

Nachricht

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)

Fehlertyp

TypeError

Was ist schiefgelaufen?

Das Argument von Array.prototype.sort() (und seine verwandten Methoden: Array.prototype.toSorted(), TypedArray.prototype.sort(), TypedArray.prototype.toSorted()) soll entweder undefined oder eine Funktion sein, die ihre Operanden vergleicht.

Beispiele

Ungültige Fälle

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

Gültige Fälle

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

Siehe auch