【发布时间】:2013-01-31 02:57:27
【问题描述】:
我正在尝试比较两个对象的键,属性值无关紧要。
var obj1 = {
foo: {
abc: "foo.abc",
},
bar: {
aaa: {
bbb: "bar.aaa.bbb" // <-- difference
}
}
};
var obj2 = {
foo: {
abc: "foo.abc",
},
bar: {
aaa: {
ccc: "bar.aaa.ccc" // <-- difference
}
}
};
// function should return true if properties are identical, false otherwise
function compareObjProps(obj1, obj2) {
for(var prop in obj1) {
// when comparing bar.aaa.bbb and bar.aaa.ccc
// this does get logged, but the function doesn't return false
if(!obj2.hasOwnProperty(prop)) {
console.log("mismatch found");
return false;
}
if(typeof(obj1[prop]) === "object") {
compareObjProps(obj1[prop], obj2[prop]);
}
}
// this always returns
return true;
}
看来return false不是从顶层函数返回的,而是递归的。
那么当整个匹配函数执行完毕后如何返回false呢?
【问题讨论】:
-
你怎么知道它没有返回false?你评估返回值吗?
-
@MeNoMore
var result = compareObjPros(obj1, obj2); console.log(result);总是正确的...
标签: javascript function recursion return