题解 | #表格排序#
表格排序
https://www.nowcoder.com/practice/a23d261947194d5d8e2687aa873d96e4
1. 易读
2. 排序灵活
function sort(type, order) { const tbody = document.getElementById("jsList"); const trs = Array.from(document.querySelectorAll("#jsList tr")); let data = []; for (let i = 0; i < trs.length; i++) { let tds = Array.from(trs[i].childNodes); data.push({ id: tds[0].innerHTML, price: tds[1].innerHTML, sales: tds[2].innerHTML, tr: trs[i] }); } data.sort((a, b) => { if (order == "asc") return a[type] - b[type]; else if (order == "desc") return b[type] - a[type]; else return 0; }); tbody.innerHTML = ''; data.forEach(item => { tbody.appendChild(item.tr); }); return data; }