为什么我使用moment.js得到一个无休止的循环



我得到了以下字符串数组:

队列日期=

[
'2020-11', '2021-01',
'2021-02', '2021-03',
'2021-04', '2020-10',
'2021-05', '2020-12',
'2021-07'
]

现在我试着用以下代码对日期进行排序,从2020-10到2021-07按升序排列:

cohortsDates.forEach((month) => {
for(var i = 0; i < cohortsDates.length; i++ ) {
if(moment(cohortsDates[i+1]) < moment(cohortsDates[i])) {
var swap = cohortsDates[i]
cohortsDates[i] = cohortsDates[i+1]
cohortsDates[i+1] = swap

}
}
})
console.log(cohortsDates)

但我得到的只是一个无休止的循环,排序后的数组永远不会打印出来。有人知道吗?我该怎么办?

i === cohortsDates.length-1(即,您正在查看for循环中的最后一项(时,您测试:

if(moment(cohortsDates[i+1]) < moment(cohortsDates[i])) {

其中cohortsDates[i+1]将始终是undefined并且因此小于先前的值。

因此,交换它们并将cohortsDates[i]分配给cohortsDates[i+1]

这将cohortsDates.length增加1,因此for循环的结束条件不适用。

现在再次循环,cohortsDates[i+1]仍然是undefined,所以它变为无穷大。


JS有一个内置的sort方法来实现这一点。不要重新发明轮子。

您并没有最有效的排序算法。排序时,应该使用javascript的array.sort:

cohortsDates.sort((a, b) => moment(a) < moment(b) ? -1 : 1);

sort方法将在数组上循环,并调用作为参数传递的函数,其中两个值作为参数。如果函数返回负数,则表示a小于b,正数表示a大于b

相关内容

最新更新