当前位置 : 主页 > 网络编程 > JavaScript >

js判断两个数组内容的类型是否一致(顺序可以不同)

来源:互联网 收集:自由互联 发布时间:2021-06-28
arraysSimilar.js function arraysSimilar(arr1, arr2){ if(!(arr1 instanceof Array) || !(arr2 instanceof Array)){ return false; } if(arr1.length != arr2.length){ return false; } var i=0,n=arr1.length,countMap1={},countMap2={},t1,t2,TYPES=['str
arraysSimilar.js
function arraysSimilar(arr1, arr2){
    if(!(arr1 instanceof Array) || !(arr2 instanceof Array)){
        return false;
    }
    
    if(arr1.length != arr2.length){
        return false;
    }
    
    var i=0,n=arr1.length,countMap1={},countMap2={},t1,t2,TYPES=['string','boolean','number','undefined','null','function','date','window'];
    
    for(;i < n;i++){
        t1 = typeOf(arr1[i]);
        t2 = typeOf(arr2[i]);
        if(countMap1[t1]){
            countMap1[t1]++;
        } else {
            countMap1[t1] = 1;
        }
        if(countMap2[t2]){
            countMap2[t2]++;
        } else {
            countMap2[t2] = 1;
        }
    }
    
    function typeOf(ele){
        var r;
        if (ele === null) r='null';
        else if (ele instanceof Array) r='array';
        else if (ele === window) r='window'
        else if (ele instanceof Date) r = 'date'
        else r = typeof ele;
        return r;
    }
    
    for (i = 0,n = TYPES.length;i < n;i++){
        if(countMap1[TYPES[i]] !== countMap2[TYPES[i]]){
            return false;
        }
    }
    
    return false;
}
网友评论