请在index.html文件中,编写arraysSimilar函数,实现判断传入的两个数组是否相似。具体需求:
-
数组中的成员类型相同,顺序可以不同。例如[1, true] 与 [false, 2]是相似的。
-
数组的长度一致。
-
类型的判断范围,需要区分:String, Boolean, Number, undefined, null, 函数,日期, window.
/*
* 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;
else if(arr1.length == arr2.length && arr1.length == 0) return true;
var arr1Types = getTypes(arr1);
var arr2Types = getTypes(arr2);
var arr1TypesCount = Object.keys(arr1Types).length;
var arr2TypesCount = Object.keys(arr2Types).length;
// 判断类型个数是否一致
if(arr1TypesCount!=arr2TypesCount) return false;
for(var item in arr1Types){
if(!arr2Types[item]) return false;
}
return true;
}
function getTypes(arr){
var types = {};
for(var a1 of arr){
if(typeof(a1)!="object"){
types[typeof(a1)] = typeof(a1);
}else{
// 如果是object
var temp = Object.prototype.toString.apply(a1);
switch(temp){
case "[object Array]":
temp = "array";
break;
case "[object Function]":
temp = "function";
break;
case "[object Date]":
temp = "date";
break;
case "[object Window]":
temp = "window";
break;
case "[object Undefined]":
temp = "undefined";
break;
case "[object Null]":
temp = "null";
break;
case "[object Object]":
// 考虑仅为object的情况
temp = "object";
break;
}
types[temp] = temp;
}
}
return types;
}