我想比較兩個對象的鍵,屬性的值並不重要。如何擺脫遞歸函數內的for循環並返回Javascript?
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?
你怎麼知道它diesn't返回false?你評估回報價值嗎? – CloudyMarble 2013-02-15 06:45:40
@MeNoMore'var result = compareObjPros(obj1,obj2); console.log(result);'始終爲真... – user1643156 2013-02-15 06:50:22