表排序负数

时间:2018-01-29 20:47:50

标签: javascript sorting

我有这段代码link

function sortTable(table, col, reverse) {
    var tb = table.tBodies[0],
        tr = Array.prototype.slice.call(tb.rows, 0),
        i;
    reverse = -((+reverse) || -1);
    tr = tr.sort(function (a, b) { 
        return reverse 
            * (a.cells[col].textContent.trim() 
                .localeCompare(b.cells[col].textContent.trim(), undefined, {numeric: true})
               );
    });
    for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]);
}

function makeSortable(table) {
    var th = table.tHead, i;
    th && (th = th.rows[0]) && (th = th.cells);
    if (th) i = th.length;
    else return; 
    while (--i >= 0) (function (i) {
        var dir = 1;
        th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
    }(i));
}

function makeAllSortable(parent) {
    parent = parent || document.body;
    var t = parent.getElementsByTagName('table'), i = t.length;
    while (--i >= 0) makeSortable(t[i]);
}

window.onload = function () {makeAllSortable();};

这是对表中的记录进行排序的代码,但是当我在表中时,负数排序无法正常工作。例如,我有数字:-132-112320.240.4322423432

脚本按顺序排序desc24234320.4320.24-11232-132

asc-132-112320.240.4322423432

但它应该是正确的-11232-1320.240.4322423432

演示:jsfiddle

1 个答案:

答案 0 :(得分:0)

您正在排序字符串类型的值。使用parseFloat()转换为数字。