Question (Eloquent JS 2nd Ed, Chapter 4, Exercise 4):
Write a function, deepEqual, that takes two values and returns true only if they are the same value or are objects with the same properties whose values are also equal when compared with a recursive call to deepEqual.
Test Cases:
var obj = {here: {is: "an"}, object: 2};
var obj1 = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj,obj1));
Code:
var deepEqual = function (x, y) {
if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
if (Object.keys(x).length != Object.keys(y).length)
return false;
for (var prop in x) {
if (y.hasOwnProperty(prop)){
if (! deepEqual(x[prop], y[prop])) //should not enter!!
return false;
alert('test');
}else return false; // What does this section do?
}
return true;
}
else if (x !== y)
return false;
else
return true;
};
Originaly fulfilled by Paul Roub
Main question: I just added alert to the block of code after if (! deepEqual(x[prop], y[prop]))
statement like kind of debugging, and now I have no idea why code inside is still executed while the statement itself is supposed to return true
and !
turns it false
..?
In addition: What is }else return false;
for? (same statement) The function seems to work fine without this section..
Aucun commentaire:
Enregistrer un commentaire