思路数组
Array.prototype.unique = function() { var res = [this[0]]; for (var i = 1; i < this.length; i++) { var repeat = false; for (var j = 0; j < res.length; j++) { if (this[i] == res[j]) { repeat = true; break; } } if (!repeat) { res.push(this[i]); } } return res; } var arr = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']; console.log(arr.unique())
思路微信
先将原数组进行排序this
检查原数组中的第i个元素与结果数组中的最后一个元素是否相同(由于已经排序,因此重复元素会在相邻位置)spa
若是不相同,则将该元素存入结果数组中prototype
Array.prototype.unique = function() { this.sort(); // 排序 var res = [this[0]]; for (var i = 1; i < this.length; i++) { if (this[i] !== res[res.length - 1]) { res.push(this[i]); } } return res; } var arr = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']; console.log(arr.unique())
这种方法会在去重以前进行排序,因此最后返回的结果也是排序以后的。若是要求不改变数组的顺序去重,这种方法是不可取的。code
思路对象
至于如何对比,就是每次从原数组中取出一个元素,而后到对象中去访问这个属性,若是能访问到值,说明重复了。blog
Array.prototype.unique = function() { var res = [this[0]], obj = {}; for (var i = 1; i < this.length; i++) { if (!obj[this[i]]) { res.push(this[i]); obj[this[i]] = 1; } } return res; } var arr = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!']; console.log(arr.unique())
这种方法效率最高,在处理长数组的时候颇有优点,推荐使用。排序
感兴趣的能够扫码关注微信公众号:io
你还有什么好的方法,能够告诉我,谢谢~~