1、双for去重
Array.prototype.Duplicate = function() { let arr = this; for(let i = 0; i < arr.length-1; i++) { for (let j = i+1; j < arr.length; j++) { if (arr[i] == arr[j]) { arr.splice(j, 1); j--; // 删除元素之后,需要将数组的长度也减1,否则无法去除掉后面相同的值. }; }; }; return arr; }
2、利用递归去重
Array.prototype.Duplicate = function() { let arr = this; arr.sort(); function loop(index) { if (index > 1) { if (arr[index] == arr[index-1]) { arr.splice(index, 1); }; loop(index-1); }; }; loop(arr.length-1); return arr; }
3、利用对象去重
Array.prototype.Duplicate = function() { let arr = this; let obj = {} let arr2 = [] for (let i = 0; i < arr.length; i++) { if (!obj[arr[i]]) { obj[arr[i]] = true; arr2.push(arr[i]); } }; return arr2; }
4、利用indexOf
Array.prototype.Duplicate = function() { let arr = this; let arr2 = [] for (let i = 0; i < arr.length; i++) { if (arr2.indexOf(arr[i]) == -1) { arr2.push(arr[i]); } }; return arr2; }
5、利用es6 includes方法判断
Array.prototype.Duplicate = function() { let arr = this; let arr2 = []; for (let i = 0; i < arr.length; i++) { if (!arr2.includes(arr[i])) { arr2.push(arr[i]); } } return arr2 }