數組去重復
阿新 • • 發佈:2017-06-02
light char blog push fun cti console oct length
舉例
數組 [1,1,7,4] 去重,並且去掉重復的選項為 [7,4]
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Document</title> </head> <body> <script> Array.prototype.unique3 = function(){ var res = []; var json = {}; var count = 0 ; var obj = {}; for(var i = 0; i < this.length; i++){ if(!json[this[i]]){ //未存 res.push(this[i]); json[this[i]] = ++count; }else{ //已存 if(!obj[this[i]]){ //首次 obj[this[i]] = 1; for(var j=0;j<res.length;j++){ if(res[j]==this[i]){ res.splice(j,1) } } } } } return res; } var arr = [1,1,7,4,7]; console.log(arr.unique3()); </script> </body> </html>
數組去重復