<!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>