题解 | #数组排序#
数组排序
https://www.nowcoder.com/practice/18ea36ef9b0c470e9db7681eced6e8df
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <button class='up'>销量升序</button> <button class='down'>销量降序</button> <ul></ul> <script> var cups = [ { type: 1, price: 100, color: 'black', sales: 3000, name: '牛客logo马克杯' }, { type: 2, price: 40, color: 'blue', sales: 1000, name: '无盖星空杯' }, { type: 4, price: 60, color: 'green', sales: 200, name: '老式茶杯' }, { type: 3, price: 50, color: 'green', sales: 600, name: '欧式印花杯' } ] var ul = document.querySelector('ul'); var upbtn = document.querySelector('.up'); var downbtn = document.querySelector('.down'); renderList(ul, cups) // 补全代码 upbtn.onclick = function () { cups.sort(function(a,b) { return a.sales - b.sales }) renderList(ul, cups) } downbtn.onclick = function () { cups.sort(function (a, b) { return b.sales - a.sales }) renderList(ul, cups) } function renderList(dom, list) { if (!list || list.length <= 0) return let str = '' let len = list.length for (let i = 0; i < len; i ++) { str += '<li>' + list[i].name + '</li>' } dom.innerHTML = str } </script> </body> </html>#你觉得今年春招回暖了吗##23届找工作求助阵地##软件开发薪资爆料##我的实习求职记录#