function sort(type, order) { // 获取需要排序的列的索引 const theadIndex = Array.from(document.querySelectorAll('th')).findIndex(item=> item.innerText == type) // 获取所有节点 const tableDom = document.querySelector('#jsList') const jsList = tableDom.children // 获取需要排序的列 const targetList = Array.from(jsList).map(item=>{ return Number(item.children[theadIndex].innerText) }) // 排序方法 function setRank (arr = []){ if (arr.length <= 1) { return arr } const min = [] const max = [] const center = arr.splice(Math.floor(arr.length / 2), 1)[0] for (let i=0; i<arr.length; i++) { const item = arr[i].children[theadIndex].innerText if (item <= center.children[theadIndex].innerText) { min.push(arr[i]) } else { max.push(arr[i]) } } const front = order == 'desc' ? setRank(max) : setRank(min) const end = order == 'desc' ? setRank(min) : setRank(max) return [...front, center, ...end] } const list = setRank(Array.from(jsList)) list.map(item=>{ tableDom.appendChild(item) }) }
用以上方法,我自己运行是可以的,不知道为什么跑用例有时候不通过,欢迎大佬指正