我使用 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);
}
问题是表格仅按第一个数字排序,如下所示:
[ 1, 10, 12, 18, 2, 3, 33, 4, 5]
我希望它是这样的
[ 1, 2 , 3, 4, 5, 10, 12, 18, 33]
最佳答案
有一个选项对象可以提供给 localeCompare 方法。假定其选项之一表明您也可以比较数字('1' < '2' < '10')。 基本用法如下:
a.localeCompare(b, 'en', {numeric: true})
你的代码可以这样修改
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);
}
检查链接以找出 localeCompare 方法的可能选项:
关于javascript - localeCompare 排序时未检测到整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51060910/