岩纸剪刀递归

时间:2015-08-01 19:59:18

标签: javascript recursion

var rockPaperScissors = function(rounds) {
  var outcomes = [];
  var plays = ['rock', 'paper', 'scissors'];
  var playedSoFar = [];

  var combos = function(roundsToGo) {
    // base case
    if (roundsToGo === 0) {
      outcomes.push(playedSoFar.slice());
      return;
    }

    for (var i = 0; i < plays.length; i++) {
      playedSoFar.push(plays[i]);
      combos(roundsToGo - 1);
      playedSoFar.pop();
    }
  };
  combos(rounds);
  return outcomes;
};

console.log(rockPaperScissors(2));

如果我从slice()取出playedSoFaroutcomes只会返回9个空数组,而不是2轮石头剪刀游戏中的所有组合:

[ [ 'rock', 'rock' ],
  [ 'rock', 'paper' ],
  [ 'rock', 'scissors' ],
  [ 'paper', 'rock' ],
  [ 'paper', 'paper' ],
  [ 'paper', 'scissors' ],
  [ 'scissors', 'rock' ],
  [ 'scissors', 'paper' ],
  [ 'scissors', 'scissors' ] ]

当我从slice()中取出playedSoFar时,为什么这不起作用?

2 个答案:

答案 0 :(得分:1)

.slice()会返回您的数组的副本,如果您不使用.slice()并只推送playedSoFar数组,那么其更新的内容将反映在整个范围内,因此它们将会反映在combos数组中。更多详情here

答案 1 :(得分:1)

如果你想保留playingSoFar,那么这就是你要走的路:

  outcomes=outcomes.concat(playedSoFar);