<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>數組去重</title> </head> <body> <script type="text/javascript"> function array_dedup(arr){ return Array.from(new Set(arr)); } let arr=array_dedup([1,2,3,3,4,5,5,6]); console.log(arr);//1,2,3,4,5,6 </script> </body> </html>
使用此方法很是簡單,通俗易懂。該方法主要利用了Set內部結構的原理,而後經過Array.from()方法將set轉換爲數組,一點就通。javascript
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>數組去重</title> </head> <body> <script type="text/javascript"> let arrs=[1,2,3,4,5,5,6]; function arraydedep(arr){ let temp=[]; for(let i=0;i<arr.length;i++){ if(temp.indexOf(arrs[i])==-1){ temp.push(arrs[i]) } } return temp; } let arr=arraydedep(arrs); console.log(arr);//1,2,3,4,5,6 </script> </body> </html>
這一種方法可能在我開發過程當中遇到最多的方法吧!html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>數組去重</title> </head> <body> <script type="text/javascript"> let arr=[1,2,2,3,3,4,5]; let unique=[...new Set(arr)]; console.log(unique);//輸出1,2,3,4,5 </script> </body> </html>
此方法更是舒服,代碼簡單,容易上手和閱讀。java