1.使用ES6的Set进行去重
<!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转换为数组,一点就通。
2.使用indexof去重
<!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>
3.扩展运算符和Set实现去重
<!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>
网友评论