天天看點

數組中排序元素的方式

方式一:

 <script>

       const arr = [1, 2, 1, 3, 2, 2, 4, 5, 5, 6, 7]

       // 擷取數組中的元素

       // for(let i=0; i<arr.length; i++){

       //     const index = arr.indexOf(arr[i], i+1)

       //     if(index !== -1){

       //         // 出現重複内容

       //         arr.splice(index, 1)

       //         i--

       //     }

       // }

       // console.log(arr)

       const newArr = []

       for(let ele of arr){

           if(newArr.indexOf(ele) === -1){

               newArr.push(ele)

           }

       }

       console.log(newArr)

       /*  

           有一個數組:

               [9,1,3,2,8,0,5,7,6,4]

           編寫代碼對數組進行排序 --> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

       */

   </script>

方式二:​

let xx_arr = [1, 7, 8, 4, 3];

console.log(xx_arr.length)

     xx_arr.sort(function (a, b) {

       // 降序

       return b - a

    // 升序

    // return a- b

     })

     console.log(xx_arr)