javascript - 在 JavaScript 中使用排序方法时是否应该检查数组长度?

标签 javascript arrays sorting

我对 JavaScript 中的 array.sort() 方法有疑问。数组中的值集可以从 1 到更多不等。如果有多个元素,Sort 函数应按顺序对它们进行排序。这是我的代码:

var myDates = ["03/05/2017","02/01/2017","03/02/2017"];

myDates.sort(function(a,b) {
    a = a.split('/').reverse().join('');
    b = b.split('/').reverse().join('');
    return a > b ? 1 : a < b ? -1 : 0;
});

上面的代码工作正常,所有日期都已排序。我的问题是我应该在运行排序方法之前检查数组的长度吗?我问这个问题是因为我的数组在某些情况下只能有一个元素。到目前为止,当我仅使用一个元素进行测试时,我的代码没有抛出任何错误,但我想知道是否应该在运行 sort() 之前检查数组的长度,否则 JavaScript 已经接受了关心那个?如果有人知道答案请告诉我。谢谢。

最佳答案

此行为记录在 Array.prototype.sort 规范中。请参阅http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort

具体:

The arguments for calls to SortCompare are values returned by a previous call to the [[Get]] internal method, unless the properties accessed by those previous calls did not exist according to HasOwnProperty. If both perspective arguments to SortCompare correspond to non-existent properties, use +0 instead of calling SortCompare. If only the first perspective argument is non-existent use +1. If only the second perspective argument is non-existent use −1.

简而言之:

Array.prototype.sort((未定义, 未定义) => { ... });//=> 0

Array.prototype.sort((未定义, b) => { ... });//=> 1

Array.prototype.sort((a, undefined) => { ... });//=> -1

关于javascript - 在 JavaScript 中使用排序方法时是否应该检查数组长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42662136/

相关文章:

javascript - 在 Node.js 中处理回滚的 MySQL 事务

javascript - Woocommerce 通过 ajax 添加到购物车 - 502 错误网关响应

javascript - 选择字段 OnChange,使 <tr> 显示/隐藏,最初显示但一旦消失,无法重新显示

java - 在JAVA中这种排序叫什么?

php - 如何像在 php 中一样将 URL 变量传递给 express.js?

c# - 从抽象类型对象数组访问特定子类的对象

javascript - angularjs - 从输入选择中删除选项

arrays - 无法读取数组的属性

javascript - 更优雅的数组二次排序

vb.net - 在vb.net中的datagridview中添加行号