javascript排序将中间项放在顶部 [英] javascript sort placing middle item at top

查看:79
本文介绍了javascript排序将中间项放在顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下排序功能:

var timeArray = new Array('11:41', '11.39', '11:41', '11:41', '11:40', '11:70', '11:39', '11:38', '11:38', '11:37', '11:37');

timeArray.sort(function(c, d) {
        var digit1 = parseInt(c.replace(/\D/g,''));
        var digit2 = parseInt(d.replace(/\D/g,''));
        return  digit1 > digit2;});

var testContent = '';
for (var i = 0; i < timeArray.length; i++) {
    testContent += timeArray[i] + '<br />';
}

$('#test').html(testContent);

我希望看到以下结果:

11:37
11:37
11:38
11:38
11.39
11:39
11:40
11:41
11:41
11:41
11:70

但是,11.70数字始终显示在结果的顶部。如果我更改了数组中的 11:70 值,无论我使用什么值,它总是出现在结果的开头。

However, the 11.70 number always appears at the top of the results. If I change the 11:70 value in the array, no matter what value I use that is the one that will always appear at the start of the results.

有谁知道我如何正确排序这个以及为什么11:70总是出现在列表顶部?

Does anyone know how I can sort this properly and why the 11:70 always appears at the top of the list?

示例小提琴

推荐答案

将排序功能更改为

timeArray.sort(function(c, d) {
    var digit1 = parseInt(c.replace(/\D/g,''));
    var digit2 = parseInt(d.replace(/\D/g,''));
    return  digit1 - digit2;
});

FIDDLE

预计会返回一个数字,而不是布尔值。

It's expecting a number to be returned, not a boolean.

https:// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

这篇关于javascript排序将中间项放在顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆