localeCompare 排序时未检测到整数

Nem*_*nja 5 javascript jquery laravel

我使用 JS 和 jQuery 对我的表进行排序,这是我对表进行排序的代码

function sortTable(table, column, order) {
        var asc = order === 'asc';
        var tbody = table.find('tbody');

        tbody.find('tr').sort(function (a, b) {
            if (asc) {
                return $('td:eq(' + column + ')', a).text()
                    .localeCompare($('td:eq(' + column + ')', b).text());
            } else {
                return $('td:eq(' + column + ')', b).text()
                    .localeCompare($('td:eq(' + column + ')', a).text());
            }
        }).appendTo(tbody); 
    }
Run Code Online (Sandbox Code Playgroud)

问题是该表仅按第一个数字排序,如下所示:

[ 1, 10, 12, 18, 2, 3, 33, 4, 5]
Run Code Online (Sandbox Code Playgroud)

我希望它是这样的

[ 1, 2 , 3, 4, 5, 10, 12, 18, 33]
Run Code Online (Sandbox Code Playgroud)

Kir*_*lov 16

有一个选项对象可以提供给 localeCompare 方法。假定其选项之一表明您也可以比较数字('1' < '2' < '10')。基本用法如下:

a.localeCompare(b, 'en', {numeric: true})
Run Code Online (Sandbox Code Playgroud)

你的代码可以这样修改

function sortTable(table, column, order) {
        var asc = order === 'asc';
        var tbody = table.find('tbody');

        tbody.find('tr').sort(function (a, b) {
            if (asc) {
                return $('td:eq(' + column + ')', a).text()
                    .localeCompare($('td:eq(' + column + ')', b).text(), 'en', {numeric: true});
            } else {
                return $('td:eq(' + column + ')', b).text()
                    .localeCompare($('td:eq(' + column + ')', a).text(), 'en', {numeric: true});
            }
        }).appendTo(tbody); 
    }
Run Code Online (Sandbox Code Playgroud)

检查链接以找出 localeCompare 方法的可能选项:

Intl.Collat​​or() 构造函数

String.prototype.localeCompare()


Nik*_*aut 1

因为如果您想将其视为数字对该列进行更改,则它被视为字符串,假设column1,或者如果您有多个数字列,那么您可以在数组中检查它,假设 if is forvar check_col = [1,2,5];

 tbody.find('tr').sort(function (a, b) {
        if (asc) {
            if(column==1){ // if check_col.indexOf(column) > -1 for multiple numeric column
               return parseInt($('td:eq(' + column + ')', a).text()) - parseInt($('td:eq(' + column + ')', b).text());
            }else{
               return $('td:eq(' + column + ')', a).text()
                .localeCompare($('td:eq(' + column + ')', b).text());
            }
        } else {
            if(column==1){ // if check_col.indexOf(column) > -1 for multiple numeric column
               return parseInt($('td:eq(' + column + ')', b).text()) - parseInt($('td:eq(' + column + ')', a).text());
            }else{
               return $('td:eq(' + column + ')', b).text()
                .localeCompare($('td:eq(' + column + ')', a).text());
            }
        }
    }).appendTo(tbody); 
Run Code Online (Sandbox Code Playgroud)