weixin_慕沐3317972
2021-05-18 18:27
function arraysSimilar(arr1, arr2){
if (arr1.length !== arr2.length) {
return false;
}else{
for (el1 of arr1) {
let type1 = Object.prototype.toString.call(el1);
let stepPaired = false;
for (el2 of arr2) {
let type2 = Object.prototype.toString.call(el2);
if (type1 === type2) {
const index = arr2.indexOf(el2);
arr2.splice(index,1);
stepPaired = true;
break;
}
}
if (!stepPaired) {
return false;
}
}
}
return true;
}
/*
* param1 Array
* param2 Array
* return true or false
*/
function arraysSimilar(arr1, arr2) {
if (
Object.prototype.toString.apply(arr1) === '[object Array]' &&
Object.prototype.toString.apply(arr2) === '[object Array]' &&
arr1.length === arr2.length
) {
var arr_1 = [];
var arr_2 = [];
for (var i = 0; i < arr1.length; i++) {
arr_1[i] = Object.prototype.toString.apply(arr1[i]);
arr_2[i] = Object.prototype.toString.apply(arr2[i]);
}
arr_1 = arr_1.sort();
arr_2 = arr_2.sort();
if (JSON.stringify(arr_1) === JSON.stringify(arr_2)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
//兄台的代码,我阅读之后觉得有问题,如果两个数组元素的类型是一致的,但是由于顺序不同就会运行失败!我运行了一下试试,确实没成功!
<!DOCTYPE HTML><html><head> <meta http-equiv="Content-Type" content="text/html; charset=gb18030"> <title>Untitled Document</title> </head><body> <script type="text/javascript"> /* * param1 Array * param2 Array * return true or false */ function arraysSimilar(arr1, arr2){ if(!(arr1 instanceof Array) || !(arr2 instanceof Array)) { return false; } if(arr1.length != arr2.length) { return false; } var arr1Lx = []; var arr2Lx = []; for(var i = 0;i<arr1.length;i++) { arr1Lx.push(Object.prototype.toString.apply(arr1[i])); } for(var j = 0;j<arr2.length;j++) { arr2Lx.push(Object.prototype.toString.apply(arr2[j])); } arr1Lx = Array.from(new Set(arr1Lx)); arr2Lx = Array.from(new Set(arr2Lx)); let arr3Lx = Array.from(new Set(arr1Lx.concat(arr2Lx))); if ((arr2Lx.length != arr1Lx.length) || (arr3Lx.length != arr1Lx.length) || (arr3Lx.length != arr2Lx.length)) { return false; } else { console.log('类型一样'); return true; } } </script> <script src="testData.js"></script></body></html>
JavaScript深入浅出
281112 学习 · 1020 问题
相似问题