JS 数组去重的几个方法
1 Array.prototype.unique1 = function () { 2 var n = []; //一个新的临时数组 3 for (var i = 0; i < this.length; i++) //遍历当前数组 4 { 5 //如果当前数组的第i已经保存进了临时数组,那么跳过, 6 //否则把当前项push到临时数组里面 7 if (n.indexOf(this[i]) == -1) n.push(this[i]); 8 } 9 return n; 10 }; 11 12 13 Array.prototype.unique2 = function() 14 { 15 var n = {},r=[]; //n为hash表,r为临时数组 16 for(var i = 0; i < this.length; i++) //遍历当前数组 17 { 18 if (!n[this[i]]) //如果hash表中没有当前项 19 { 20 n[this[i]] = true; //存入hash表 21 r.push(this[i]); //把当前数组的当前项push到临时数组里面 22 } 23 } 24 return r; 25 }; 26 27 28 Array.prototype.unique3 = function() 29 { 30 var n = [this[0]]; //结果数组 31 for(var i = 1; i < this.length; i++) //从第二项开始遍历 32 { 33 //如果当前数组的第i项在当前数组中第一次出现的位置不是i, 34 //那么表示第i项是重复的,忽略掉。否则存入结果数组 35 if (this.indexOf(this[i]) == i) n.push(this[i]); 36 } 37 return n; 38 }; 39 40 41 Array.prototype.unique4 = function() 42 { 43 this.sort(); 44 var re=[this[0]]; 45 for(var i = 1; i < this.length; i++) 46 { 47 if( this[i] !== re[re.length-1]) 48 { 49 re.push(this[i]); 50 } 51 } 52 return re; 53 }; 54 55 56 var arr = [1,2,2,2,3,3,4,5]; 57 console.log(arr.unique1()); // [1, 2, 3, 4, 5] 58 console.log(arr.unique2()); // [1, 2, 3, 4, 5] 59 console.log(arr.unique3()); // [1, 2, 3, 4, 5] 60 console.log(arr.unique4()); // [1, 2, 3, 4, 5]
[-_-]眼睛累了吧,注意劳逸结合呀[-_-]

分类:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?