问题描述
我得到以下字符串数组:
cohortsDates =
[
'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 有一个 built-in sort
method 来做到这一点。不要重新发明轮子。
您没有最有效的排序算法。排序时,应该使用javascript的array.sort
:
cohortsDates.sort((a,b) => moment(a) < moment(b) ? -1 : 1);
sort
方法将遍历数组并调用您作为参数传递的函数,其中两个值作为参数。如果函数返回负数,则表示 a
小于 b
,正数表示 a
大于 b
。