原生js—数组去重
<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"><title>Document</title></head><body>去除数组里面重复的元素<p>arr = [1, 2, 1, 3, 2, 5, 4, 6]</p><button id=\"xh\">循环去重</button><p id=\"xh_html\">这里是循环去重的内容</p><hr /><button id=\"indexOf\">indexOf去重</button><p id=\"indexOf_html\">这里是indexOf去重的内容</p><hr /><button id=\"jianzhi\">jianzhi去重</button><p id=\"jianzhi_html\">这里是jianzhi去重的内容</p><hr /><button id=\"qianyi\">每一项与剩下的比较去重</button><p id=\"qianyi_html\">这里是每一项与剩下的比较去重的内容</p><hr /><button id=\"es6\">es6的set去重</button><p id=\"es6_html\">这里是es6的set去重的内容</p><script>var arr = [1, 2, 1, 3, 2, 5, 4, 6, 56, 56, 78, 9, 19]var oXh = document.querySelector(\'#xh\');var oIndexOf = document.querySelector(\'#indexOf\');var ojianzhi = document.querySelector(\'#jianzhi\');var qianyi = document.querySelector(\'#qianyi\');var es6 = document.querySelector(\'#es6\');var oXh_html = document.querySelector(\'#xh_html\');var oIndexOf_html = document.querySelector(\'#indexOf_html\');var jianzhi_html = document.querySelector(\'#jianzhi_html\');var qianyi_html = document.querySelector(\'#qianyi_html\');var es6_html = document.querySelector(\'#es6_html\');// 比较简单的循环去重function uniqArr(arr) {for (var i = 0; i < arr.length; i++) {for (var j = i + 1; j < arr.length - 1; j++) {if (arr[i] === arr[j]) {// console.log(\'同\')arr.splice(i, 1)}}}return arr}oXh.onclick = function () {// console.log(oXh_html.innerHTML)oXh_html.innerText = uniqArr(arr)}// 通过indexof实现去重function Index(arr) {let newArr = []for (var i = 0; i < arr.length; i++) {if (newArr.indexOf(arr[i]) < 0) {newArr.push(arr[i])}}return newArr}oIndexOf.onclick = () => {// console.log(oIndexOf_html.innerText)// console.log(Index(arr))oIndexOf_html.innerText = Index(arr)}function ObjArr(arr) {let obj = {}let newArr = []for (var i = 0; i < arr.length; i++) {if (!obj[arr[i]]) {obj[arr[i]] = 1newArr.push(arr[i])}}return newArr}ojianzhi.onclick = function () {jianzhi_html.innerText = ObjArr(arr)}// 通过前一项与剩下的比较function nextCom(arr) {let newArr = [arr[0]]for (var i = 1; i < arr.length; i++) {let flag = falsefor (var j = 0; j < newArr.length; j++) {if (newArr[j] === arr[i]) {flag = truebreak}}if (!flag) newArr.push(arr[i])}return newArr}qianyi.onclick = function () {qianyi_html.innerText = nextCom(arr)}// es6Set去重function Es6(arr) {return Array.from(new Set(arr))}// console.log(Es6(arr))es6.onclick = function () {es6_html.innerText = Es6(arr) + \'---new Set()方法不允许有重复的数据,但是返回的是一个类数组,所以需要通过Array.from()转换成数组\'}</script></body></html>