【问题标题】:Wrong array method sort() logic错误的数组方法 sort() 逻辑
【发布时间】:2018-07-06 18:51:15
【问题描述】:

我无法理解数组方法sort() 的逻辑。我必须为AgeLetter 这两个元素编写一个eventListener。通过单击它们,我们可以按年龄和字母对表格进行排序。

一切正常,但我在sort() 逻辑中看到了一些奇怪的东西。通过单击Letter - 表必须按字母排序Letter 列中的元素。通过单击Age - 表必须按数字顺序对Age 列中的元素进行排序。但它排序不正确。

tbody = document.getElementById('grid');

function tableSort(event) {

  var target = event.target;
  var action = target.getAttribute('data-type');
  var arr = [].slice.call(grid.rows, 1);
  var self = this;

  this.number = function() {

    arr.sort(function(a, b) { // sort by digits in the column "Age"
      a.cells[0].innerHTML;
      b.cells[0].innerHTML;

      return a - b;
    });

    grid.appendChild(...arr);
  }

  this.string = function() {

    arr.sort(function(a, b) { // sort by words in the column "Letter"
      a.cells[1].innerHTML;
      b.cells[1].innerHTML;

      return a > b;
    });

    grid.appendChild(...arr);
  }

  if (action) {
    self[action]();
  }
}

tbody.addEventListener('click', tableSort);
th {
  cursor: pointer;
}
<table id="grid">
  <thead>
    <tr>
      <th data-type="number">Age</th>
      <th data-type="string">Letter</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>5</td>
      <td>BBBBB</td>
    </tr>
    <tr>
      <td>12</td>
      <td>AAAAA</td>
    </tr>
    <tr>
      <td>1</td>
      <td>DDDDD</td>
    </tr>
    <tr>
      <td>9</td>
      <td>CCCCC</td>
    </tr>
    <tr>
      <td>2</td>
      <td>KKKKK</td>
    </tr>
  </tbody>
</table>

<script>
</script>

【问题讨论】:

  • a.cells[0].innerHTML; 是空操作
  • 顺便说一句,垂直的称为“列”而不是“行”。
  • @Bergi 感谢您突出我的自动错误。但这不是解决方案。以前我尝试过letters 的另一种方式,但它也无济于事:arr.sort((a, b)=&gt;{ return a.cells[1].innerHTML &gt; b.cells[1].innerHTML ? 1 : -1; });
  • 您可以从文档中获得一些灵感,sort - 它显示了如何处理字符串,以及您可能需要的数字parseInt

标签: javascript arrays sorting


【解决方案1】:

修改了您的代码并使其正常工作。如果您需要,请在这里:

  function tableSort(event) {
    var target = event.target;
    var action = target.getAttribute("data-type");
    var arr = [].slice.call(grid.rows, 1);
    var self = this;

    this.number = function() {
      arr.sort(function(a, b) {
        // sort by digits in the column "Age"
        return Number(a.cells[0].innerHTML) - Number(b.cells[0].innerHTML);
      });

      arr.forEach(function(item, index) {
        grid.appendChild(item);
      });
    };

    this.string = function() {
      arr.sort(function(a, b) {
        // sort by words in the column "Letter"
        var str1 = a.cells[1].innerHTML;
        var str2 = b.cells[1].innerHTML;
        return str1.localeCompare(str2);
      });

      arr.forEach(function(item, index) {
        grid.appendChild(item);
      });
    };

    if (action) {
      self[action]();
    }
  }

  tbody.addEventListener("click", tableSort);

【讨论】:

    【解决方案2】:

    this stackoverflow post Sorting HTML table with JavaScript 进行澄清以及我在其中找到完整示例的原始外部文章怎么样?

    Sorting tables with VanillaJS 或 JQuery

    例子:

    /**
     * Modified and more readable version of the answer by Paul S. to sort a table with ASC and DESC order
     * with the <thead> and <tbody> structure easily.
     * 
     * https://stackoverflow.com/a/14268260/4241030
     */
    var TableSorter = {
        makeSortable: function(table){
            // Store context of this in the object
            var _this = this;
            var th = table.tHead, i;
            th && (th = th.rows[0]) && (th = th.cells);
    
            if (th){
                i = th.length;
            }else{
                return; // if no `<thead>` then do nothing
            }
    
            // Loop through every <th> inside the header
            while (--i >= 0) (function (i) {
                var dir = 1;
    
                // Append click listener to sort
                th[i].addEventListener('click', function () {
                    _this._sort(table, i, (dir = 1 - dir));
                });
            }(i));
        },
        _sort: function (table, col, reverse) {
            var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
            tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
            i;
    
            reverse = -((+reverse) || -1);
    
            // Sort rows
            tr = tr.sort(function (a, b) {
                // `-1 *` if want opposite order
                return reverse * (
                    // Using `.textContent.trim()` for test
                    a.cells[col].textContent.trim().localeCompare(
                        b.cells[col].textContent.trim()
                    )
                );
            });
    
            for(i = 0; i < tr.length; ++i){
                // Append rows in new order
                tb.appendChild(tr[i]);
            }
        }
    };
    
    window.onload = function(){
        TableSorter.makeSortable(document.getElementById("myTable"));
    };
    table thead th {
    cursor: pointer;
    
    }
    <table id="myTable">
    <thead>
        <th data-type="string">Name</th>
        <th data-type="number">Age</th>
    </thead>
    <tbody>
        <tr>
        <td>John</td>
        <td>42</td>
      </tr>
        <tr>
        <td>Laura</td>
        <td>39</td>
      </tr>
        <tr>
        <td>Fred</td>
        <td>18</td>
      </tr>
        <tr>
        <td>Bod</td>
        <td>26</td>
      </tr>
    </tbody>
    </table>

    【讨论】:

    • 我已经使用了您链接中的示例,但它们也无济于事。此外,对于这种情况,我必须只使用 JS 解决方案
    • OP 有一个数字列,考虑也解决这个问题。
    猜你喜欢
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多