题解 | #数组排序#

数组排序

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');
            // 补全代码
            const sortFn = (event)=>{
        console.log(event);
        while(ul.hasChildNodes()) {
            ul.removeChild(ul.firstChild)
        }
        if(event == 'up') {
            cups.sort((a, b) => {
          return a.sales - b.sales;
        });
        }
        if(event == 'down') {
            cups.sort((a, b) => {
          return b.sales - a.sales;
        });
        }
       
        cups.map((item) => {
      let lis = document.createElement("li");
      lis.innerHTML = `${item.name}`
      ul.appendChild(lis)
        });
      };
      upbtn.onclick = function() {
         sortFn('up')
        
      }
      downbtn.onclick = function() {
        return sortFn('down')
      }
        </script>
    </body>
</html>

全部评论

相关推荐

头像
11-06 10:58
已编辑
门头沟学院 嵌入式工程师
双非25想找富婆不想打工:哦,这该死的伦敦腔,我敢打赌,你简直是个天才,如果我有offer的话,我一定用offer狠狠的打在你的脸上
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务