javascript递归变量问题
我最近使用javascript编写了MinMax算法,但是当我实现递归时 变量的变化似乎很奇怪,下面是代码:javascript递归变量问题,javascript,Javascript,我最近使用javascript编写了MinMax算法,但是当我实现递归时 变量的变化似乎很奇怪,下面是代码: function moveValue(istate, move, moveFor, nextTurn, depth){ console.log("the original state is: ", istate) var state = stateMove(istate, move, nextTurn); var winner = status.detectWi
function moveValue(istate, move, moveFor, nextTurn, depth){
console.log("the original state is: ", istate)
var state = stateMove(istate, move, nextTurn);
var winner = status.detectWin(state)
console.log("now the istate is:", istate)
console.log("now the state is: ", state)
if (winner == 'tie'){
return 0;
} else if (winner != 0){
if (moveFor == nextTurn) return 10 - depth;
else return depth - 10;
}
//if the the current operation is not the same with the original, minimum scenario
//if the the current operation is the same with the original, maximum scenario
var hope = 999;
if (moveFor != nextTurn) hope = -999;
var moves = getLegalMoves(state);
for (var i=0; i<9; i++){
if (moves.indexOf(i) > -1) {
var value = moveValue(state, i, moveFor, -nextTurn, depth+1);
if (moveFor == nextTurn && value < hope ||moveFor != nextTurn && value > hope ){
hope = value;
}
}
}
return hope;
}
stateMove
函数在这里,firstPlayer、secondPlayer与单元格的方式相同
function stateMove(state, move, nextTurn){
var value = firstPlayer;
if (nextTurn == -1) value = secondPlayer;
state[move] = value
return state
}
stateMove
函数正在变异传递给它的数组。将其更改为创建阵列副本将解决此问题:
function stateMove(state, move, nextTurn){
var nextState = state.slice(0);
var value = firstPlayer;
if (nextTurn == -1) value = secondPlayer;
nextState[move] = value;
return nextState;
}
我怀疑您的
stateMove
函数正在更改istate
数组,而不是复制它。如果你为这个函数添加代码,它会使问题更容易诊断。嗨,@musicaly\u ut,我添加了它,谢谢你的回答哇,你能解释一下吗?它如何更改参数传递的状态?结束了吗?但这在音乐上太不典型了_ut@user3526776除了原语之外,Javascript几乎是一种通过引用传递的语言。因此,如果更改传递的对象(数组也是对象+细节)的任何属性(请记住,索引值也是属性),则原始值将被更改。这里的解释更加完整:非常感谢!我被困在这里一整天了!谢谢again@user3526776没问题。此外,正是您的调试技能使您的解决方案达到了一英寸的高度。
function stateMove(state, move, nextTurn){
var value = firstPlayer;
if (nextTurn == -1) value = secondPlayer;
state[move] = value
return state
}
function stateMove(state, move, nextTurn){
var nextState = state.slice(0);
var value = firstPlayer;
if (nextTurn == -1) value = secondPlayer;
nextState[move] = value;
return nextState;
}