错误的数组方法sort()逻辑

时间:2018-01-27 16:58:40

标签: javascript arrays sorting

我无法理解数组方法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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

修改了您的代码并使其正常运行。如果您需要,请点击这里:

  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);

答案 1 :(得分:1)

此stackoverflow帖子 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>