RangeError:JS函数中的最大调用堆栈大小错误

时间:2015-12-25 21:51:29

标签: javascript underscore.js

  function findRandomDayIndex() {
    var dayindex = _.random(0, 39);
    var slot = dayslots[dayindex]; // array of 40 objects
    if(slot.filled === true || slot === undefined) {
      return findRandomDayIndex();
    } else {
      return dayindex;
    } 
  }

我收到错误:

  

RangeError:最大调用堆栈大小超过了同一函数的迭代次数

如何更好地编写函数?

4 个答案:

答案 0 :(得分:4)

你可以尝试这个版本

 $new = "SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE   table_name = 'Professors' ORDER BY column_name";

   while($row = mysql_fetch_array($new)) {  
    $output = $row['column_name'] . "<br>";
    echo $output;
}

请检查天图的一致性,以防止无限循环

答案 1 :(得分:1)

您不需要递归来执行此操作。通过一些重构,您可以映射数组以保存索引,然后过滤未定义和填充的值,然后从该新数组中获取随机项,例如:

SockJS

答案 2 :(得分:0)

这是一个处理所有时段被填满的人。示例代码返回-1,但您可以更新它以返回任何内容。

function findRandomDayIndex() {
    // Create an array of indexes for items that aren't filled
    var m = _.map(dayslots, function(v, k) {
        if (!v.filled) {
            return k;
        }
    });
    // The array will have undefined for those already filled, so we use lodash without to remove them
    m = _.without(m, undefined);
    if (m.length === 0) {
        // Handle when all slots are filled
        return -1;
    } else {
        // return a random index
        return m[_.random(0, m.length)];
    }
}

// Lets create some test data
var dayslots = [];
for (var i = 0; i < 40; i++) {
    dayslots.push({
        filled: false
    });
}

// Test our function    
console.log(findRandomDayIndex());

如果将填充更改为true,则会得到-1。

答案 3 :(得分:0)

由于@CodeiSir发表评论,因为没有插槽是免费代码进入无限循环。所以我改变了下面的代码,它工作正常。谢谢!

      if (_.findWhere(dayslots, {filled: false}) !== undefined) {
          var dayindex = _.random(0, 39); 
          var slot = dayslots[dayindex];
          console.log(dayslots.length);
          if(slot.filled === true || slot === undefined) {
            return findRandomDayIndex();
          } else {
            return dayindex;
          } 
        }