好的,我已经解决了这个问题:我创建了一个对象来定义我的复杂对象应该是什么样子。一种蓝图。
var structure = {
property1: {id:"name", type:"string", required:false},
property2: {
id:"categories", type:"object", required:true,
content:{
property1:{
type:"object", min:1,
content:{
property1:{id:"depth", type:"positiveinteger", required:false},
property2:{
id:"groups", type:"object", required:true,
content:{
property1:{
type:"array", min:1,
content:{
type:"object", min:1,
content:{
property1:{id:"myFunction", type:"function", required:true},
property2:{id:"args", type:"array", required:false},
}
}
}
}
}
}
}
}
}
}
然后我运行比较蓝图(“结构”)与对象要测试的功能(“DEF”):
function compareStructure(struct, def){
if(isArray(def)){
if(isDefined(struct.min) && def.length < struct.min){ alert("Error in structur check: " + " min is " + struct.min + "."); return false}
if(isDefined(struct.max) && def.length > struct.max){ alert("Error in structur check: " + " max is " + struct.max + "."); return false}
for(var i = 0; i < def.length; i++){
compareStructure(struct.content, def[i]);
}
} else {
for(var k in struct){
if(struct[k].id){
propFound = false;
for(var m in def) if(m == struct[k].id) propFound = m;
if(!propFound && struct[k].required){ alert("Error in structure check: " + struct[k].id + " not defined."); return false}
if(propFound && !verifyThis(struct[k], def[propFound], propFound)) return false;
if(propFound && struct[k].content) compareStructure(struct[k].content, def[propFound]);
} else {
for(var m in def){
if(!verifyThis(struct[k], def[m], m)) return false;
if(struct[k].content) compareStructure(struct[k].content, def[m]);
}
}
}
}
}
function verifyThis(struct, def, prop){
// This is where the checks for types and values are made.
}
比较函数在进展仍然可以工作,但这就是我现在要做的概念。
可能会更好[codereview](http://codereview.stackexchange.com/) – Neal 2011-05-13 15:01:38
“最好”真的是一个可回答的问题吗?你认为什么会使一种技术比另一种更好? – Malvolio 2011-05-13 15:01:40
@Neal:codereview.se以何种方式适合此? OP目前没有任何他们试图改进的代码。 – 2011-05-13 15:05:39