我使用此代碼對各種類型的數據(日期、數字、字符串等)進行排序。它在大多數情況下都有效,但是當我嘗試對包含負數的數字的列進行排序時,它無法正確排序。假設我喜歡按降序對第 3 列進行排序。就像現在一樣,它排序為 0,負數將被忽略。 function sortcolumn(value) { // alert(value) let table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0; table = document.getElementById("ControlPanelListOfPAGAVEISPendentesTable"); switching = true; dir = "desc"; while (switching) { switching = false; rows = table.rows; for (i = 1; i < (rows.length - 1); i++) { shouldSwitch = false; x = rows[i].cells[value].textContent.trim().toLowerCase(); y = rows[i + 1].cells[value].textContent.trim().toLowerCase(); const num = /^\d/.test(x) const date = num && x.indexOf("/") != -1; if (date) { let [dd, mm, yyyy] = x.split("/"); x = new Date(yyyy, mm - 1, dd, 15, 0, 0, 0).getTime(); [dd, mm, yyyy] = y.split("/"); y = new Date(yyyy, mm - 1, dd, 15, 0, 0, 0).getTime(); } else if (num) { x = +x.replace(",", ".") y = +y.replace(",", "."); } if (dir == "asc") { shouldSwitch = x > y } else if (dir == "desc") { shouldSwitch = x < y } if (shouldSwitch) break; } if (shouldSwitch) { rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; switchcount++; } else { if (switchcount == 0 && dir == "asc") { dir = "desc"; switching = true; } } }}table { border-spacing: 0; width: 100%; border: 1px solid #ddd;}th, td { text-align: left; padding: 1px;}tr:nth-child(even) { background-color: #f2f2f2}
如何在 javascript 中對帶有負數的表進行排序
料青山看我應如是
2022-12-09 15:09:07