js去重函数(封装函数)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>数组去重</title> <style> .main{ } .one, .two{ background-color: aqua; width: 100px; height: 100px; float: left; } .two{ background-color: blueviolet; } .erjiu{ width: 1000px; height: 50px; background-color: chartreuse; } .claerfix::after{ content: ''; clear: both; display: block; height: 0; visibility: hidden; } </style> </head> <body> <div class="main claerfix"> <div class="one"></div> <div class="two"></div> </div> <div class="erjiu"></div> </body> <script> // var arrys=['c','a','z','a','x','a','x','c','b']; // 封装去重函数 function selectArry(arrys){ var newArry=[]; //创建新的空数组 for(i=0;i<arrys.length;i++){ //遍历旧数组 // newArry.push(arrys); if(newArry.indexOf(arrys[i])===-1){ //如果新数组里没有旧数组里的某个元素 // 使用indexOf()是因为如果遇到重复元素会自动选择第一个元素 // 添加到新数组后也不会打乱旧数组的顺序 newArry.push(arrys[i]); //就把该元素添加到新数组里 } } return newArry; //返回新数组 } // 调用函数 var one=selectArry(['c','a','z','a','x','a','x','c','b']) ; console.log(one); // console.log(newArry); //['c', 'a', 'z', 'x', 'b'] </script> </html>