原生js—数组去重
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a8a5772b4c7caaeddd50ab7d5bd46e6c.png)
<!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]) {
arr.splice(i, 1)
}
}
}
return arr
}
oXh.onclick = function () {
oXh_html.innerText = uniqArr(arr)
}
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 = () => {
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]] = 1
newArr.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 = false
for (var j = 0; j < newArr.length; j++) {
if (newArr[j] === arr[i]) {
flag = true
break
}
}
if (!flag) newArr.push(arr[i])
}
return newArr
}
qianyi.onclick = function () {
qianyi_html.innerText = nextCom(arr)
}
function Es6(arr) {
return Array.from(new Set(arr))
}
es6.onclick = function () {
es6_html.innerText = Es6(arr) + '---new Set()方法不允许有重复的数据,但是返回的是一个类数组,所以需要通过Array.from()转换成数组'
}
</script>
</body>
</html>