Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. JavaScript
  3. JavaScript 参考
  4. JavaScript 错误参考
  5. TypeError: invalid Array.prototype.sort argument

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

TypeError: invalid Array.prototype.sort argument

JavaScript 异常“invalid Array.prototype.sort argument”会在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 或用于比较其操作数的函数。

示例

无效示例

js
[1, 3, 2].sort(5); // TypeErrorstudents.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));

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp