<!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');
            // 补全代码

            // order为0升序,order为1降序
            function compare(key, order) {
                return function(a, b){
                    if(order == 0){
                      return a[key] - b[key]
                    }else{
                      return b[key] - a[key]
                    }
                }
             }
            // 清空元素
            function clear(){
                // 需要清空多少个要先知道
                var len = ul.children.length
                for(let i=0; i<len; i++){
                  ul.removeChild(ul.children[0])
                }
            }
   
            // 渲染封装为函数
            function Render(arr){
                for(let i=0; i<arr.length; i++){
                    var item = document.createElement("li")
                    item.innerText = arr[i].name
                    ul.appendChild(item)
                }
            }
            // 第一次渲染
            Render(cups)
            
            // 点击按钮后重新渲染
            upbtn.onclick = function(){
                var newCups = cups.sort(compare("sales", 0))
                // 先清除
                clear()
                Render(newCups)
               
            }
            downbtn.onclick = function(){
                var newCups = cups.sort(compare("sales", 1))
                clear()
                Render(newCups)
            }
            
        </script>
    </body>
</html>