<!DOCTYPE html><html>
<head>
<title>数组去重</title>
<script type="text/javascript">
//已知如下数组:
// var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
// 编写一个程序将数组扁平化去并除其中重复部分数据,最终得到一个升序且不重复的数组
window.onload=function() {
//var divs = document.getElementById('divPrint');
var arr = [
[1, 2, 2],
[3, 4, 5, 5],
[6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
var arr1 = new Array();
var n = 0;
//使用Array.prototype.eachall 遍历出多维数组,赋值给一个新的一位数组,将数组扁平化
arr.eachall(function(item) {
arr1[n] = item;
n += 1;
});
var i = arr1.length,
j;
var temp;
while (i > 0) { //冒泡排序
for (j = 0; j < i - 1; j++) {
if (arr1[j] == arr1[j + 1]) {
arr1.remove(arr1[j]);
}
if (arr1[j] > arr1[j + 1]) {
temp = arr1[j];
arr1[j] = arr1[j + 1];
arr1[j + 1] = temp;
}
} i--;
}
//遍历输出去重之后的数组
for (let index = 0; index < arr1.length; index++) {
document.getElementById('divPrint').innerText += arr1[index] + ",";
}
//刪除数组中的某一个元素的构造方法
Array.prototype.remove = function(val) { v
ar index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
//遍历多维数组的构造方法eachall
Array.prototype.eachall = function(fn) { t
ry {
//声明一个计数器
this.i || (this.i = 0)
//判断数组是否存在且传的值是一个函数
if (this.length > 0 && fn.constructor == Function) {
//循环
while (this.i < this.length) {
var e = this[this.i];
//判断当前值是不是数组,如果是数组进行递归e.eachall,否则执行回调函数fn.call
if (e && e.constructor == Array) {
e.eachall(fn);
} else {
fn.call(e, e);
};
this.i++;
}
//回收计数器,变量回收
this.i = null;
};
} catch (err) {
console.log("have error:" + err); //错误处理
}
};
</script></head>
<body>
<div id="divPrint"></div>
</body>
</html>
JavaScript多维数组去重
最新推荐文章于 2024-03-18 07:49:34 发布