数组去重

 1     var arr = [1, 2, 3, 4, 8, 7, 4, 5, 1, 5, 7, 55, 12, 5, 1]
 2     
 3     function unique(arr = []) {
 4       if (isArrayFn(arr) !== '[object Array]') {
 5         return alert('请传入正确的数组')
 6       }
 7       let newArr = []
 8       for (let i = 0; i < arr.length; i++) {
 9         if (newArr.indexOf(arr[i]) == -1) {
10           newArr.push(arr[i])
11         }
12       }
13       newArr.sort(function (a, b) {
14         return a - b
15       })
16       return newArr
17     }
18     function isArrayFn(o) {
19       return Object.prototype.toString.call(o)
20     }
21     console.log(unique(arr))

// 执行结果: [1, 2, 3, 4, 5, 7, 8, 12, 55]

posted @ 2021-11-29 15:51  王依一  阅读(14)  评论(0)    收藏  举报