树创建的Javascript递归

时间:2015-04-28 13:59:42

标签: javascript function recursion tree scope

我正在尝试创建用于在游戏中的每个节点中创建具有游戏状态的决策树的功能(无论什么游戏)。我写了这样的递归函数(DFS):

function makeTree(anchor,count,player){
    var subTree=null;
    var nodes=[];
    if(player)var newPlayer=false;
    else var newPlayer=true;
    for (var i = 0; i <= 9; i++) {
        for (var j = 0; j <= 9; j++) {
            if(anchor["state"][i][j]==0){
                var newState=anchor["state"];
                if(player)newState[i][j]=1;
                else newState[i][j]=2;
                var node={name:i+"_"+j, contents:[],state:newState, value:null, player:newPlayer};
                if(count>0){
                    var newCount=count-1;
                    subTree=makeTree(node,newCount,newPlayer);
                    node["contents"]=subTree;
                }
                nodes.push(node);
            }else{
                continue;
            }
        }
    }
    return nodes;
}

通过电话:

var tree={};
var hrac=true;
var plocha=[[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0]];
var state=plocha;
    tree={name: "root",
          contents:[], 
          state:state, 
          value:null, 
          player: hrac};
    tree["contents"]=makeTree(tree,3,hrac);

但是函数改变了不同范围内的变量,所以输出树将是这样的:

"root" - node - node - node
                     - node
                     - node
                     - node
                     - node

我无法弄清楚该函数中变量newState的情况,因为在完成递归后,原始变量plocha具有最新node["state"]的值。有什么建议吗?

编辑:感谢Bergi,我意识到我需要对其进行make引用的数组的深层复制,所以我为数组副本制作了功能,现在这个工作正常。谢谢Bergi!

1 个答案:

答案 0 :(得分:0)

您的state属性是一个可变的数组。在每个赋值中,您更改一个多维数组,该数组是所有节点的state。您希望将每个newState设为一个新数组,而不是递归传递所有函数的plocha引用:

 …
 var newState = anchor["state"].slice(); // create copy of the outer array
 newState[i] = newState[i].slice(); // copy of the row to be modified
 newState[i][j] = player ? 1 : 2;
 …