所以我试图采用类似的数组
["2015/10","2015/1","2015/6","2015/12","2015/3","2015/7","2015/2","2016/1","2015/8","2015/5","2015/11","2015/9","2015/4"]
,其中XXXX/YY
是年/月格式,并从最小到最大排序.
尝试使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort作为参考:
month_keys.sort(function(x,y){ var partsX = x.split('/'), partsY = y.split('/'); return partsX[0] < partsY[0] ? -1 : ( partsX[1] < partsY[1] ? -1 : 1 ); })...
这给了我
["2015/1","2015/11","2016/1","2015/10","2015/12","2015/2","2015/3","2015/5","2015/5","2015/6","2015/7","2015/8","2015/9"]
在我开头给出的示例数组中.我究竟做错了什么?
您正在比较字符串,而不是数字.在比较字符串时,它们会按字符比较char,所以任何以1开头的东西都会出现在例如2之前.即使它是10比2.
将它们转换为数字,您应该得到您想要的订单:
var partsX = +x.split('/'), partsY = +y.split('/');
您还需要修复实际比较:
if (partsX[0] < partsY[0]) return -1; else if (partsX[0] > partsY[0]) return 1; else if (partsX[1] < partsY[1]) return -1; else if (partsX[1] > partsY[1]) return 1; else return 0;