Javascript - deepEqual Comparison

后端 未结 8 1302
囚心锁ツ
囚心锁ツ 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:47

    You can use a variable outside the for loop to keep track of the comparison:

    var allPropertiesEqual = true;
    for (var prop in x) {
        if (y.hasOwnProperty(prop)) {
            allPropertiesEqual = deepEqual(x[prop], y[prop]) && allPropertiesEqual;
        } else {
            allPropertiesEqual = false;
        }
    }
    return allPropertiesEqual;
    

    The previous example is not optimized on purpose. Because you're comparing objects, you know that you can return false as soon as you find an inequality, and you can keep looping while all the previous checked properties are equal:

    for (var prop in x) {
        if (y.hasOwnProperty(prop)) {
            if (! deepEqual(x[prop], y[prop]) )
                return false; //first inequality found, return false
        } else {
            return false; //different properties, so inequality, so return false
        }
    }
    return true;
    

提交回复
热议问题