如果while循环条件为<;6(即一个循环),但如果将其设置为<6;7个或更多(即1个以上回路)
var data = {
a: "abc",
c: 0
}
function recurse(data, nodes) {
const first = nodes.shift();
console.log("first-"+first.id, first.t);
if (first.t == "action") {
data.c = data.c + 1;
console.log("exec action", data.c);
} else {
switch (first.t) {
case "if_else":
console.log(recurse(data, first.b[0].actions), 300);
break
case "while":
var brNodes = first.b[0].actions
while (data.c < 7) {
console.log(recurse(data, brNodes), 400);
}
break
default:
break
}
}
return (nodes.length > 0)? console.log(recurse(data, nodes), 200): "Completed"
}
var actions = [
{id:1, t:"action", b:null},
{id:2, t:"action", b:null},
{id:3, t:"if_else", b:[{id:31, t:"branch", actions:[{id:311, t:"action", b:null}, {id:312, t:"action", b:null}]},{id:32, t:"branch", actions:[{id:321, t:"action", b:null}]}]},
{id:4, t:"action", b: null},
{id:5, t:"while", b:[{id:500, t:"branch", actions:[{id:511, t:"action", b:null}]}]},
{id:6, t:"action", b:null}
]
console.log(recurse(data, actions), 100)
下面是我在StackBlitz上的测试https://StackBlitz.com/edit/recurse?file=index.js
您的代码是这样做的:
const first = nodes.shift();
然后尝试访问:
first.b[0].actions
并且,nodes.shift()
从nodes
数组中删除第一个元素。节点数组有6个项。如果您试图通过将条件设置为while(data.c<7)
来调用函数7次,则在最后一次迭代时,您将得到一个空的nodes
数组,从而在first
中有一个未定义的
值,并且当您的代码在最后一次迭代时尝试访问first.b[0].actions
时,这将导致错误。