gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:50:52 26 4
gpt4 key购买 nike

我对 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com