1. 通过ES6新增数据类型Set的特性
Array.prototype.unique = function() { return [...new Set(this)]; };
2. 通过for循环+indexOf过滤,并用新开辟的存储空间保存合适的数组元素
Array.prototype.unique = function() { const result = []; for (let i = 0, len = this.length; i < len; i++) { // 或 result.includes(this[i]) --> return true/false if (result.indexOf(this[i]) === -1) result.push(this[i]); } return result; };
3. 借助hash算法的思想
Array.prototype.unique = function() { const record = {}; const result = []; const len = this.length; let curr, i; for (i = 0; i < len; i++) { curr = this[i]; if (record[curr]) continue; record[curr] = true; result.push(curr); } return result; };