JavaScript变量在定义后更改为结果

问题描述 投票:1回答:1

我正在创建一个用筷子自己玩的计算机机器人。我发明了一个while循环运行,直到其中一台计算机获胜。我将计算机的gameState存储在一个看起来像[[1,1],[1,1]]的变量中。列表中的第一项是玩家一,他的左手和右手值是1.第二个玩家是相同的方式。然而,在我定义gameState,我console.log() gameState变量并获得游戏的最终结果之后的行,我将其定义为[[1,1],[1,1]]之后的行。这个问题是在while循环期间,我无法获得有关计算机正在进行的移动的信息。救命!

这是我的代码:

function makeMove(s, player, m) { //source, player, move
  //if it is player 2, flip it around
  if (player == 2) {
    var s = [s[1], s[0]];
  }
  var target;
  var source;

  //move 0 is when the left hand targets the opponent's right hand
  //move 1 is when the right hand targets the opponent's left hand
  //move 2 is when the left hand targets the opponent's left hand
  //move 3 is when the right hand targets the opponent's right hand

  //the state [[1,1],[1,1]] stores the values of each hand and each opponent

  if (m == 0 || m == 3) {
    target = [1, 0];
  } else {
    target = [1, 1];
  }
  if (m == 0 || m == 2) {
    source = [0, 0];
  } else {
    source = [0, 1];
  }
    s[target[0]][target[1]] += s[source[0]][source[1]];
    s[target[0]][target[1]] %= 5;

  if (player == 2) {
    s = [s[1], s[0]];
  }
  return s;
}

function playmatch() {
  //the original state, 
  var gameState = [[1, 1], [1, 1]];
  //right after I create the value, for some reason it changes to the end result when I log it the next line.
  console.log(gameState);
    var winner = -1;
   while (winner == -1) {
     var choice = [0,1,2,3];
      var move = choice[Math.floor(Math.random() * choice.length)];
      gameState = makeMove(gameState, 1, move);
     var move = choice[Math.floor(Math.random() * choice.length)];
      gameState = makeMove(gameState, 2, move);
      if (gameState[0][0] == 0 && gameState[0][1] == 0) {
      winner = 2;
    }
    if (gameState[1][0] == 0 && gameState[1][1] == 0) {
      winner = 1;
    }
     console.log(gameState);
    }
return winner;
  }
playmatch();

和codepen笔的链接:https://codepen.io/gmoyer/pen/EeepbE

javascript
1个回答
4
投票

console.log的行为不规范。正如MDN所建议的,你应该serialize your object

做这个

console.log(JSON.parse(JSON.stringify(obj)));

代替

console.log(obj);

确保传递给console.log的内容是该时刻对象的快照,而不是对象的引用。我假设console.log在你调用它时没有正确执行,并且给出了对你的数组的引用。因此,您的数组会更改,稍后当console.log执行时,它会记录更改的数组。

© www.soinside.com 2019 - 2024. All rights reserved.