zhangxinxu / quiz

小测答题收集区
536 stars 43 forks source link

解答 #12

Closed uaison closed 5 years ago

uaison commented 5 years ago

第一题

function equalObject(obj1, obj2){
    let str1 = JSON.stringify(obj1);
    let str2 = JSON.stringify(obj2);
    if(str1===str2) return true;
    if(str1.length!=str2.length) return false;
    let a = str1.substring(1,str1.length-1);
    let b = str2.substring(1, str2.length-1);
    return a.split(',').every(item => b.indexOf(item)>-1)
}

第二题

function equalArray(arr1, arr2) {
    return arr1.every((item,index)=>item===arr2[index]);
}

第三题

function equal(arg1, arg2) {
    let type1 = Object.prototype.toString.call(arg1);
    let type2 = Object.prototype.toString.call(arg2);
    if(type1 !== type2) return false;
    if(type1 === '[object Array]')
        return arg1.every((item, index) => equalObject(item, arg2[index]));
    if(type1 === '[object Object]') {
        let keys1 = Object.keys(arg1);
        let keys2 = Object.keys(arg2);
        if(keys1.length!==keys2.length) return false;
        return keys1.every(key => {
            if(Object.prototype.toString.call(arg1[key]) === '[object Object]')
                return equalObject(arg1[key], arg2[key]);
            if(Object.prototype.toString.call(arg1[key]) === '[object Array]')
                return equalArray(arg1[key], arg2[key]);
            return arg1[key] === arg2[key];         
        })
    }
}