简体   繁体   English

在JavaScript中使用排序方法时,应该检查数组长度吗?

[英]Should I check array length when using sort method in JavaScript?

I have a question about array.sort() method in JavaScript. 我对JavaScript中的array.sort()方法有疑问。 Set of values in the array can vary from 1 to more. 数组中的值集可以从1到更大。 Sort function should sort them in the order if there is more than one element. 如果有多个元素,则排序功能应按顺序对其进行排序。 Here is my code: 这是我的代码:

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

Code above works fine, all dates are sorted. 上面的代码工作正常,所有日期均已排序。 My question is should I check the length of the array before I run the sort method? 我的问题是在运行sort方法之前是否应该检查数组的长度? I'm asking this because my array can have one element only in some situations. 我之所以这样问是因为我的数组只能在某些情况下具有一个元素。 So far my code did not throw any errors when I tested with one element only, but I would like to know if I should check the length of the array before I run the sort() or JavaScript already takes care of that? 到目前为止,当我仅使用一个元素进行测试时,我的代码没有引发任何错误,但是我想知道是否应该在运行sort()之前检查数组的长度,或者JavaScript已经解决了这个问题? If anyone knows the answer please let me know. 如果有人知道答案,请告诉我。 Thank you. 谢谢。

This behaviour is documented in the Array.prototype.sort specification. Array.prototype.sort规范中记录了此行为。 See http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort 参见http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.sort

Specifically: 特别:

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. 调用SortCompare的参数是先前对[[Get]]内部方法的调用返回的值,除非根据HasOwnProperty不存在那些先前调用所访问的属性。 If both perspective arguments to SortCompare correspond to non-existent properties, use +0 instead of calling SortCompare. 如果两个SortCompare的透视图参数都对应于不存在的属性,请使用+0而不是调用SortCompare。 If only the first perspective argument is non-existent use +1. 如果只有第一个视角参数不存在,请使用+1。 If only the second perspective argument is non-existent use −1. 如果仅第二个透视图参数不存在,请使用-1。

In short: 简而言之:

Array.prototype.sort((undefined, undefined) => { ... }); // => 0

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM