JS递归函数问题

时间:2015-09-27 16:03:57

标签: javascript function recursion

我似乎无法在过去和当前相同时重复这一点(这是一个新的报价生成器)。

    function random() { // random number 0-9
      var number = Math.floor(Math.random() * 9);
      return number;
    }

    var past = [0];     // array of past quotes

    function writer() { // on button click for new random quote
      var current = random();
      past.push(current);
      function checker() {
        if (past[past.length - 2] === past[past.length - 1]) {
          current = random();
          checker();
        } 
      }
      checker();
    }

1 个答案:

答案 0 :(得分:0)

Rekursiv geht meistens schief (抱歉没有英语)

如果条件为真,则未更改最后一个值:

var past = [-1]; // impossible value;

function writer() { // on button click for new random quote
  var current = random();       // get a first random
  past.push(current);           // add this to past array
  function checker() {
                                // check last two values
    if (past[past.length - 2] === past[past.length - 1]) {
      current = random();       // if equal, get a new random;
      checker();                // re-call - BUT -
                                // as there' actually no change to past,
                                // we're in an infinite loop.
    }                           
  }
  checker();
}

变化:

var past = [-1]; // impossible value;

function writer() { // on button click for new random quote
  var current = random();       // get a first random
  past.push(current);           // add this to past array
  function checker() {
                                // check last two values
    if (past[past.length - 2] === past[past.length - 1]) {
      current = random();       // if equal, set a new random even to past
      past[past.length - 1] = current;
      checker();                // re-call 
    }                           
  }
  checker();
}