Javascript - deepEqual Comparison

后端 未结 8 1300
囚心锁ツ
囚心锁ツ 2020-12-05 05:21

Question (From Eloquent Javascript 2nd Edition, Chapter 4, Exercise 4):

Write a function, deepEqual, that takes two values and returns true only if th

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 05:55

    I am quite new to JS but this is the way I solved it:

    function deepEqual(obj1, obj2) {
    if (typeof obj1 === "object" && typeof obj2 === "object") {
        let isObjectMatch = false;
        for (let property1 in obj1) {
            let isPropertyMatch = false;
            for (let property2 in obj2) {
                if (property1 === property2) {
                    isPropertyMatch = deepEqual(obj1[property1], obj2[property2])
                }
    
                if(isPropertyMatch){
                    break;
                }
            }
    
            isObjectMatch  = isPropertyMatch;
    
            if (!isObjectMatch) {
                break;
            }
        }
    
        return isObjectMatch;
    } else {
        return obj1 === obj2;
    }
    }
    

    And here are my tests:

    var obj = {here: {is: "an"}, object: 2};
    console.log(deepEqual(obj, obj));
    // → true
    console.log(deepEqual(obj, {here: 1, object: 2}));
    // → false
    console.log(deepEqual(obj, {here: {is: "an"}, object: 2}))
    // → true
    console.log(deepEqual(obj, {object: 2, here: {is: "an"}}));
    // → true
    console.log(deepEqual(obj, {object: 1, here: {is: "an"}}));
    // → false
    console.log(deepEqual(obj, {objectt: 2, here: {is: "an"}}));
    // → false
    console.log(deepEqual(2, 2));
    // → true
    console.log(deepEqual(2, 3));
    // → false
    console.log(deepEqual(2, null));
    // → false
    console.log(deepEqual(null, null));
    // → false
    console.log(deepEqual(obj, null));
    // → false
    

提交回复
热议问题