题解 | #数组排序#
数组排序
https://www.nowcoder.com/practice/18ea36ef9b0c470e9db7681eced6e8df
{"html":"<!DOCTYPE html>\r\n<html lang=\"en\">\r\n <head>\r\n <meta charset=\"UTF-8\">\r\n </head>\r\n <body>\r\n <button class='up'>销量升序</button>\r\n <button class='down'>销量降序</button>\r\n <ul></ul>\r\n\r\n <script>\r\n var cups = [\r\n { type: 1, price: 100, color: 'black', sales: 3000, name: '牛客logo马克杯' },\r\n { type: 2, price: 40, color: 'blue', sales: 1000, name: '无盖星空杯' },\r\n { type: 4, price: 60, color: 'green', sales: 200, name: '老式茶杯' },\r\n { type: 3, price: 50, color: 'green', sales: 600, name: '欧式印花杯' }\r\n ]\r\n Object.freeze(cups)\r\n var ul = document.querySelector('ul');\r\n var upbtn = document.querySelector('.up');\r\n var downbtn = document.querySelector('.down');\r\n // 补全代码\r\n let sortArr = null\r\n function sotrType (type){\r\n sortArr = [...cups]\r\n if(type === 'up'){\r\n sortArr = sortArr.sort((a,b) => a.sales - b.sales)\r\n } else if (type === \"down\") {\r\n sortArr = sortArr.sort((a,b) => b.sales - a.sales)\r\n }\r\n this.sortFun()\r\n }\r\n function sortFun (v) {\r\n let str = \"\"\r\n sortArr.forEach((item,index) => {\r\n str+= `<li>${item.name}</li>`\r\n })\r\n ul.innerHTML = str\r\n }\r\n upbtn.onclick = function () {\r\n sotrType('up')\r\n }\r\n downbtn.onclick = function (){\r\n sotrType('down')\r\n }\r\n sotrType()\r\n \r\n </script>\r\n </body>\r\n</html>","css":"/* html, body {\\n\\twidth: 100%;\\n\\theight: 100%;\\n\\tmargin: 0;\\n\\tpadding: 0;\\n} */","js":"// 请在这里输入代码"}