问题(Eloquent JS 2nd Ed,第4章,练习4):
编写一个函数deepEqual,它接受两个值,只有当它们是相同的值时返回true,或者是与对deepEqual的递归调用相比,其值也相等的对象.
测试用例:
var obj = {here: {is: "an"}, object: 2};
var obj1 = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj,obj1));
Run Code Online (Sandbox Code Playgroud)
码:
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 …Run Code Online (Sandbox Code Playgroud)