代码之家  ›  专栏  ›  技术社区  ›  Jay.

简单递归返回值

  •  1
  • Jay.  · 技术社区  · 6 年前

    我想生成一个随机整数。为了检查它是否已经生成,我想将它添加到数组中,下一次生成新整数时,我想检查它是否存在于数组中,如果它存在,然后再次生成(直到它生成不存在的整数),然后返回整数。

    我正在用下面的递归函数尝试它,但是递归不能正确工作(当它生成存在的数字时,就有问题了)。

    var ids = [];
    
    function generateID() {
    
      var newID = Math.floor(Math.random() * 6) + 1;  //small range for test
       
      if( jQuery.inArray(newID, ids) == -1 ) {
            
          ids.push(newID);     
          
          return newID;  //is it correct to return from here?
          
      } else {
        //problem part
        console.log(newID + " exists");
        generateID();    
      }  
    
    }
    
    function getID() {
    
        var i = generateID();
        console.log(i);
    
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    <button onclick="getID();" >Generate ID</button>
    1 回复  |  直到 6 年前
        1
  •  1
  •   Hemant Parashar    6 年前

    你只需要返回 generateId 在其他情况下也是如此。你也可以用 Array.includes 方法来确定数组中是否存在某些内容。

    var ids = [];
    
    function generateID() {
    
      var newID = Math.floor(Math.random() * 6) + 1; //small range for test
    
      if (!ids.includes(newID)) {
        ids.push(newID);
        return newID;
      } else {
        console.log(newID + " exists");
        return generateID();
      }
    }
    
    function getID() {
      var i = generateID();
      console.log(i);
    }
    <button onclick="getID();">Generate ID</button>