简体   繁体   English

Javascript /排序对象数组

[英]Javascript / Sort object array

I have created an 5x2 <table> with id="competitors" . 我用id="competitors"创建了一个5x2 <table>

在此处输入图片说明

I am trying to sort the competitors as objects by their position property( pos ) with the following code if onclick="sortData()" event happens: 如果发生onclick="sortData()"事件,我尝试通过以下代码按其位置属性( pos )将竞争对手分类为对象:

function getTableData() {
  var tab = document.getElementById("competitors");
  var data = [];

  for(var i=0;i<tab.rows.length;i++) {
    var competitor = {
        name: tab.rows[i].cells[0],
        pos: tab.rows[i].cells[1]
    };

    data.push(competitor);
  }

  return data; 
}

function sortData() {
  var sortedData = getTableData();
  sortedData.sort(function(a,b){
    return parseInt(a.pos) - parseInt(b.pos);
  });

  for(var i = 0; i < sortedData.length;i++) {
    console.log(sortedData[i].name.innerHTML, sortedData[i].pos.innerHTML);
  }
}

The problem is that the console prints out the same table. 问题在于控制台将打印出相同的表。 However, if i do not add the compare function, it is sorted alphabetically. 但是,如果我不添加比较功能,它将按字母顺序排序。 Please help me to understand what is going on. 请帮助我了解发生了什么。 (i have started JS yesterday ) (我昨天开始使用JS)

When sorting, you were doing parseInt of HTML elements instead of their contents. 排序时,您正在执行HTML元素的parseInt而不是它们的内容。 Here is how I would do it: 这是我的方法:

 function sortData(){ var table = document.getElementById('competitors'), data = [].slice.call(table.rows); data.sort(function(a,b){ return parseInt(a.cells[1].innerHTML, 10) - parseInt(b.cells[1].innerHTML, 10); }); for(var i=0; i<data.length; i++) { table.appendChild(data[i]); } } 
 td{ border: 1px solid #000; text-align: center; padding: .2em } 
 <table id="competitors"> <tr><td>Greg</td><td>4</td></tr> <tr><td>John</td><td>10</td></tr> <tr><td>Sarah</td><td>6</td></tr> <tr><td>Ben</td><td>2</td></tr> <tr><td>Jack</td><td>1</td></tr> </table> <br> <button onclick="sortData()">Sort</button> 

What's [].slice.call(table.rows) for? [].slice.call(table.rows)有什么用?

table.rows returns an HTMLCollection, which cannot be sorted. table.rows返回不能排序的HTMLCollection。 This allows you to convert it to an Array -> Most efficient way to convert an HTMLCollection to an Array 这使您可以将其转换为数组-> 将HTMLCollection转换为数组的最有效方法

Why use appendChild ? 为什么要使用appendChild

When you do appendChild of an element, it does not duplicate it, it moves it. 当您执行元素的appendChild时,它不会复制它,而是会移动它。 This allows you to reorder your elements. 这使您可以重新排列元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM