Javascript 循环嵌套条件被数据覆盖
我有一个JSON文件,其中包含如下对象:Javascript 循环嵌套条件被数据覆盖,javascript,loops,Javascript,Loops,我有一个JSON文件,其中包含如下对象: { "id": 23, "active": true, "state": "on", "dependency": [ { "id": 24, "type": &q
{
"id": 23,
"active": true,
"state": "on",
"dependency": [
{
"id": 24,
"type": "critical"
},
{
"id": 30,
"type": "moderate"
},
{
"id": 25,
"type": "critical"
},
{
"id": 35,
"type": "moderate"
}
]
},
依赖项值是无序的,将从其他函数中填充。此订单未排序。进一步了解依赖项的类型“选择”根SVG对象的颜色。临界值为红色[错误],中等值为黄色[有限]
如果所有“中等”条目都位于底部,则循环工作。一旦列表被混合,就像上面的例子一样。状态永远不会被“限制”,因为它会被“错误”覆盖
我创建了一个证明布尔值,应该可以避免这种情况,但每个console.log都可以教我更好的方法。任何想法,我几乎是盲目的
for (var i = 0; i < graph.nodes.length; i++) {
isModerate = false
if (graph.nodes[i].active === true && graph.nodes[i].dependency.length == 0) {
graph.nodes[i].state = "on"
} else if (graph.nodes[i].active === true && graph.nodes[i].dependency.length > 0) {
for (var j = 0; j < graph.nodes[i].dependency.length; j++) {
if (graph.nodes[i].dependency[j].type === "critical") {
if (!isModerate && graph.nodes[graph.nodes[i].dependency[j].id].state === "on") {
graph.nodes[i].state = "on"
} else if (graph.nodes[graph.nodes[i].dependency[j].id].state === "limited" || "error" || "off") {
graph.nodes[i].state = "error"
break
}
} else if (graph.nodes[i].dependency[j].type === "moderate") {
if (graph.nodes[graph.nodes[i].dependency[j].id].state === "on" ) {
graph.nodes[i].state = "on"
} else if (graph.nodes[graph.nodes[i].dependency[j].id].state === "limited" || "error" || "off" ) {
graph.nodes[i].state = "limited"
isModerate = true
}
}
}
} else if (graph.nodes[i].active === false) {
graph.nodes[i].state = "off"
}
}
for(var i=0;i0){
对于(var j=0;j
我刚刚重写了它…试图调试它是疯狂的
for(var i=0;i0){
// ------------------------------
//依赖项lsit中的项
对于(var j=0;j
我只看到4个州
那么你想用这个做什么
graph.nodes[graph.nodes[i].dependency[j].id].state === "limited" || "error" || "off"
和这个一样吗
graph.nodes[graph.nodes[i].dependency[j].id].state !== "on"
我对你的代码想做什么做了最好的猜测并重写了它
//我想这就是结构。。。
设图={
节点:[
{
“id”:23,
“主动”:正确,
“状态”:“打开”,
“依赖性”:[
{“id”:24,“type”:“critical”},
{“id”:30,“类型”:“中等”},
{“id”:25,“type”:“critical”},
{“id”:35,“类型”:“中等”}
]
},
],
};
常数
//使用字典,以便IDE可以:
//自动突出显示/全部更改/为您自动编写代码段&避免输入错误
//更容易跟踪/更改,尝试替换凌乱的字符串
状态={
关于:“关于”,
有限公司:“有限公司”,
错误:“错误”,
关:“关”,
},
类型={
关键:“关键”,
温和:“温和”,
},
//获取特定节点状态的函数
GetNodeEstate=(id)=>{
让node=graph.nodes.find(node=>node.id==id);
如果(!节点){
抛出错误(`node id:${id}未找到`);
}否则{
返回node.state;
}
};
graph.nodes.forEach(node=>{
设isModerate=false;
if(node.active){
if(node.dependency.length==0){
node.state=state.on;
}否则{
node.dependency.forEach(dependency=>{
if(dependency.type==type.critical){
如果(!isModerate&&(getNodeEstate(dependency.id)=state.on)){
node.state=state.on;
}else if(node.state!=state.on){
//我只看到4种状态,只要反转它就行了
node.state=state.error;
//这里没有中断,它将继续处理依赖项中的所有项
}
}else if(dependency.type==type.mediate){
if(getNodeEstate(dependency.id)=state.on){
node.state=state.on;
}else if(node.state!=state.on){
node.state=state.limited;