1. 程式人生 > 實用技巧 >使用氣泡排序一個表格中的數由小到大排列

使用氣泡排序一個表格中的數由小到大排列

排序前:

排序後:

程式碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <table border="1">
        <thead>
            <tr>
            <th>姓名</th>
            <th>年齡</th>
            <th>性別</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</body>
<script>
    var
arr = [ { "name":"張三", "age":20, "sex":"", }, { "name":"李四", "age":18, "sex":"", }, { "name":"王五", "age":22, "sex":"", }, ] var tmp = {}; for(var i = 0; i < arr.length-1; i++){ for
(var j = 1; j < arr.length; j++){ if(arr[i].age > arr[j].age){ tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } } } var tb = document.querySelector("table"); for(var i = 0; i < arr.length; i++){
var tr = document.createElement("tr"); for(var attr in arr[i]){ var td = document.createElement("td"); td.innerText = arr[i][attr]; tr.appendChild(td); } tb.appendChild(tr); } </script> </html>