数组sort方法实现列表的正序和倒序

tech2022-07-07  198

数组sort方法实现列表的正序和倒序

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> table { margin: 0 auto; border: 1px solid #ccc; border-spacing: 0; } th, td { width: 200px; text-align: center; border: 1px solid #ccc; } </style> </head> <body> <table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>分数</th> </tr> </thead> <tbody> </tbody> </table> <button>按照分数排序</button> <script> var tbody = document.querySelector('tbody'); var btn = document.querySelector('button'); //sort方法排序 var GZ2006 = [{ name: "刘德华", age: 20, sex: '男', score: 99 }, { name: "张学友", age: 22, sex: '男', score: 10 }, { name: "黎明", age: 26, sex: '男', score: 55 }, { name: "梁朝伟", age: 60, sex: '男', score: 20 }]; //排序 // GZ2006.sort(function(a, b) { // return a.score - b.score // }) // console.log(GZ2006); //函数的作用:循环当前数组 并将数组中的值渲染到列表中 function render() { var arr = GZ2006.map((item) => { return '<tr><td>' + item.name + '</td><td>' + item.age + '</td><td>' + item.sex + '</td><td>' + item.score + '</td></tr>' }) tbody.innerHTML = arr.join(''); } render(); //标志位 标志的是当前是正序还是倒序 var flag = true; btn.onclick = function() { if (flag) { //将数组根据score的值改成正序 GZ2006.sort((a, b) => { return a.score - b.score; }) render(); } else { //将数组根据score的值改成倒序 GZ2006.sort((a, b) => { return b.score - a.score; }) render(); } flag = !flag; } </script> </body> </html>
最新回复(0)