``` Array.prototype.distinct = function () { var arr = this, result = [], len = arr.length for (i = 0; i < len; i++) { for (j = i + 1; j < len; j++) { if (arr[i] === arr[j]) { j = ++i } } result.push(arr[i]) } return result } var arra = [1, 2, 3, 4, 4, 1, 1, 2, 1, 1, 1] arra.distinct() // [3, 4, 2, 1] ## 过滤splice 优点:简单易懂 缺点:占用内存高,速度慢 ``` javascript Array.prototype.distinct = function () { var arr = this, len = arr.length for (i = 0; i < len; i++) { for (j = i + 1; j < len; j++) { if (arr[i] === arr[j]) { arr.splice(j, 1) len-- j-- } } } return arr } var arra = [1, 2, 3, 4, 4, 1, 1, 2, 1, 1, 1] arra.distinct()
|