数组去重
Posted 盖大楼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数组去重相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js "> </script> </head> <body> <input type="text" /> <button>点击添加数据</button> </body> </html> <script> Array.prototype.unique3 = function(){ var res = []; var obj = {}; for(var i = 0; i < this.length; i++){ if(!obj[this[i]]){ res.push(this[i]); obj[this[i]] = 1; } } return res; } var arr = []; $(‘button‘).click(function() { var val = $(‘input‘).val(); arr.push(val); var result=arr.unique3(); console.log(result); }) </script>
小石头写的添加重复还要有弹窗提醒:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js "> </script> </head> <body> <input type="text" class="inputtext" /> <button>点击添加数据</button> </body> </html> <script> Array.prototype.unique3 = function() { var res = []; var obj = {}; for(var i = 0; i < this.length; i++) { if(!obj[this[i]]) { res.push(this[i]); obj[this[i]] = 1; } } return res; } var arr = []; var result = []; $(‘button‘).click(function() { var val = $(‘input‘).val(); if(val.length!=0){ for(var i = 0; i < result.length; i++) { if(val == result[i]) { alert(‘重复了‘); } }; arr.push(val); result = arr.unique3(); console.log(result); } }) </script>
以上是关于数组去重的主要内容,如果未能解决你的问题,请参考以下文章