对table进行排序

百度2019前端实习生招聘的一道编程题:根据给定table字段进行升降排序,当时做得不太好,事后再实现一遍。

当时被HtmCollection卡住了一下,建议参考NodeList v.s. HTMLCollection

完整代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<table id="jsList">
<thead>
<tr><th>id</th><th>price</th><th>sales</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>10.0</td><td>800</td></tr>
<tr><td>2</td><td>30.0</td><td>600</td></tr>
<tr><td>3</td><td>20.5</td><td>700</td></tr>
<tr><td>4</td><td>40.5</td><td>500</td></tr>
<tr><td>5</td><td>60.5</td><td>300</td></tr>
<tr><td>6</td><td>50.0</td><td>400</td></tr>
<tr><td>7</td><td>70.0</td><td>200</td></tr>
<tr><td>8</td><td>80.5</td><td>100</td></tr>
</tbody>
</table>
</body>

<script>

var tableSort = function(selector, column, order) {
var table = document.querySelector(selector);
var column_index = -1; //排序字段的索引

// 查找字段index
var th_collection = table.querySelector('thead').querySelector('tr').getElementsByTagName('th');

Array.prototype.forEach.call(th_collection, function(el, index) {
if(el.innerHTML == column){
column_index = index;
}
})

if(column_index == -1){
alert('字段不存在');
return;
}

// 获取dom collection
var dom_lines = table.querySelector('tbody').children;

// domlines 是HTML Collection对象,类数组,但不具有数组相关的方法,所以转换成数组
var lines = Array.prototype.slice.call(dom_lines, 0);

lines.sort(function(a, b) {
var a_value = a.getElementsByTagName('td')[column_index].innerHTML;
var b_value = b.getElementsByTagName('td')[column_index].innerHTML;

return order == 'asc' ? a_value - b_value : b_value - a_value;
})

var new_table = document.createElement('tbody');

lines.forEach(function(el){
new_table.appendChild(el);
});

table.replaceChild(new_table, table.querySelector('tbody'));
}

tableSort('#jsList', 'id', 'desc');

</script>
</html>