题解 | #表格排序#
表格排序
http://www.nowcoder.com/practice/a23d261947194d5d8e2687aa873d96e4
function sort(type, order) { //type为id、price或者sales; asc表示升序,desc为降序 // 1.获取父节点 var tbody = document.getElementById('jsList') // 2.获取数据--多少行数据 var len = tbody.children.length // 3.遍历获取数组 var domArr = [] var typeNum = type == 'id' ? 0 : type == 'price' ? 1 : type == 'sales' ? 2 : '' for (let i = 0; i < len; i++) { domArr.push(tbody.children[i]) } // 4.重新排列--js sort() domArr.sort((a, b) => { return order==='desc' ? (b.children[typeNum].innerHTML - a.children[typeNum].innerHTML) : (a.children[typeNum].innerHTML - b.children[typeNum].innerHTML) }) // 5.更新节点 domArr.forEach(item => { tbody.appendChild(item); }) }
- 注:刚开始写的时候第五步:更新节点,也可以达到题目要求的效果,但示例测试会报错,原来的写法如下:
// 5.更新节点 tbody.innerHTML = '' domArr.forEach(item=>{ tbody.innerHTML += item.innerHTML; })//这样写只是innerHTML相同,其他参数有区别
示例
function test() { var tbody = document.getElementById('jsList'); if (!tbody) { return false; } var count = 10; var type = 'id'; var order = 'asc'; var asc = order === 'asc'; var result = createList(tbody, count); result.sort(function (a, b) { return asc ? (a[type] - b[type]) : (b[type] - a[type]); }); sort(type, order);// var isSame = !!same(result); return isSame; //创建模拟列表 function createList(tbody, count) { var result = []; var tr = document.createElement('Tr'); var td = document.createElement('td'); var tbody = document.getElementById('jsList'); var ids = random(count); var prices = random(count); var sales = random(count); tbody.innerHTML = ''; for (var i = 0; i < count; i++) { var trLine = tr.cloneNode(); var id = ids[i]; var price = prices[i]; var sale = sales[i]; var tdId = td.cloneNode(); var tdPrice = td.cloneNode(); var tdSales = td.cloneNode(); tdId.innerHTML = id; tdPrice.innerHTML = price; tdSales.innerHTML = sale; trLine.appendChild(tdId); trLine.appendChild(tdPrice); trLine.appendChild(tdSales); tbody.appendChild(trLine); result.push({ id: id, price: price, sales: sale, tr: trLine }); } return result; } //随机生成列表数据 function random(count) { var result = []; var map = {}; var value; for (var i = 0; i < count; i++) { while (!value || map[value]) { value = Math.floor(Math.random() * 10000 + 1); } result.push(value); map[value] = true; } return result; } //判断sort()函数是否正确? function same(result) { var trs = [].slice.call(tbody.getElementsByTagName('tr') || [], 0); console.log(trs);// console.log(result); if (trs.length !== result.length) { console.log("trs.length !== result.length"); return false; } for (var i = 0; i < count; i++) { if (trs[i] !== result[i].tr) {//仅仅改变innerHTML使得trs[i]和result[i].tr不相等 return false; } } return true; } }