如何在JavaScript中对数字进行排序

Neeraj Pathak

我正在尝试在表格中使用排序。我正在使用下面给出的方法,但是使用波纹管方法对数字进行排序时出错。此方法可以正常工作,但是按数字ASC和DESC顺序发出。我不明白为什么要这样。伙计们,您对此有任何想法吗?

function sortTable(n, selector) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
///table = document.getElementById(selector);
table = $(selector);
switching = true;

//Set the sorting direction to ascending:
dir = "asc";
/*Make a loop that will continue until
no switching has been done:*/
while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = $(table).find('tr'); ///table.getElementsByTagName("TR");
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 0; i < (rows.length - 1) ; i++) {
        //start by saying there should be no switching:
        shouldSwitch = false;
        /*Get the two elements you want to compare,
        one from current row and one from the next:*/
        x = rows[i].getElementsByTagName("TD")[n];
        y = rows[i + 1].getElementsByTagName("TD")[n];
        /*check if the two rows should switch place,
        based on the direction, asc or desc:*/
        if (x != null && y != null) {
            if (dir == "asc") {
                if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                    //if so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == "desc") {
                if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
                    //if so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            }
        }
    }
    if (shouldSwitch) {
        /*If a switch has been marked, make the switch
        and mark that a switch has been done:*/
        rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
        switching = true;
        //Each time a switch is done, increase this count by 1:
        switchcount++;
    } else {
        /*If no switching has been done AND the direction is "asc",
        set the direction to "desc" and run the while loop again.*/
        if (switchcount == 0 && dir == "asc") {
            dir = "desc";
            switching = true;
        }
    }
}
}
罗布

如果要使用任何特定列对表行进行排序并按数字排序,则可以利用内置的Array.prototype.sort方法,方法是将行排序为数组,对数组进行排序,然后将行放入表中按要求的顺序。例如:

function sortMe(evt) {
  var table = this;          // Table clicked on
  var cell = evt.target;     // Cell clicked on
  var col = cell.cellIndex;  // Column number
  
  // Put rows into an array
  var rowArray = [].slice.call(table.rows);
  // Or for ECMAScript 2015
  // var rowArray = Array.from(table.rows);

  // Sort rows
  rowArray.sort(function(a, b) {
  
    // Get values of col to sort on
    a = a.cells[col].textContent;
    b = b.cells[col].textContent;

    // If numeric, sort as number
    if (isNumeric(a)) {
      return a - b;
    }
    // Other sort options here, e.g. as dates
    // Otherwise, sort as string
    return a.localeCompare(b);
  });
  
  // Put rows back in table in order
  var tbody = table.tBodies[0];
  rowArray.forEach(function (row) {
    tbody.appendChild(row);
  })

}

// Helper function
// Check if value is numeric, '2' returns true
function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

// Attach listener to table
window.onload = function() {
  document.querySelector('table').addEventListener('click', sortMe, false);
}
table {
  border-collapse: collapse;
}
td {
  border: 1px solid #bbbbbb;
  width: 5em;
}
<table>
  <tr><td>A<td>3
  <tr><td>D<td>0
  <tr><td>B<td>1
  <tr><td>C<td>2
</table>

单击任何列可对列进行排序。您可以添加其他功能,例如添加页眉和页脚,在升序和降序之间切换,处理空白单元格等。

您可能会考虑在标头单元格中使用class或data属性来控制要使用的排序类型。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在MySQL中某些字符(-)之后对数字进行排序

如何在JavaScript中按经度纬度距离对数组项进行排序?

如何在javascript中对数组进行排序?

如何在字符串列表中对数字排序?

如何在Lucene 6中对数字字段进行排序

如何在Apache Flink中对数据集进行排序?

如何在JavaScript中按日期对数组进行排序?

如何在熊猫字符串中对数字进行排序?

如何在PL / SQL中对数字表进行排序?

如何找到在JavaScript中按降序对数字数组进行排序所需的最小交换次数

如何在Unix Shell中对数字排序?

如何在TableView上对数字列表进行排序

如何在JMeter Beanshell中对数字数组进行排序

如何在C中对数字数组进行排序

如何在C ++中从对数字进行排序到按字母顺序进行排序

如何在Scala中按数字对中的第二对按降序对数字对列表进行排序?

如何在同一列Javascript中对数字和文本进行排序

在 C 中对数字进行排序

如何在 Android Studio 中对数字进行排序?

如何在 XSLT 2.0 中对数字进行排序?

如何在javascript中对数据数组进行分组和排序?

如何在Excel 2013中对数字进行排序

如何在Javascript中按属性对数组进行排序

如何在 PostgreSQL 中最后对数字进行排序?

如何在javascript中按日期名称对数组进行排序?

如何在javascript中对数字字符串进行排序?

如何在 Python 中对数组数字进行排序

如何在此代码块中从大到小对数字进行排序?

如何在python中对数组的JSON对象进行排序?