2017-07-14 178 views
1

以下Javascript已挂起。我一直在教自己的Apps脚本来对数据表进行排序。我的网站开发者朋友和我在过去的2个小时内一直无法了解为什么这个脚本停滞不前。它只是说跑步脚本永远....Google Apps脚本挂起(javascript)

发生了什么是我有一个电子表格部分指定为一个日历区域已经有一个动态日历打印到我的其他功能之一。为了测试的目的,我隔离了这个函数并给了它一个虚拟数组,但是函数应该循环遍历日历,找到'date'的COORDs(即1,2,3,4),并返回该日期之下的空单元格的坐标(我将数据放入日历的地方)。

function printCalendarValues(array){ 
    var array = [0,143,534,342,54,1,41,1]; 
    var Calendar_Display_range = recruiter_sheet.getRange('B8:H19'); 
    var Calendar_Display_values = Calendar_Display_range.getValues();  
    function getCellBelow(day, rangeArray){ 
    for(i=0; i<rangeArray.length; i++){ 
     for(j=0;j<rangeArray[i].length; j++){ 
     if(rangeArray[i][j]==day){ 
      var res = [i+9,j+2]; 
      return res; 
     };   
     }; 
    } 
    }; 
    for(i=0;i<2;i++){ //< ---- THIS IS WHERE IT BREAKS 
    // If I take the code in this for loop out of it and run it 
    // only once then it runs as expected. It breaks when I put it in 
    // this for loop. You can see I only loop twice right now. I 
    // did that for testing, but i've tried twice, or array.length 
    // anything other than running it once breaks it. 
    var cellBelow = getCellBelow(i+1, Calendar_Display_values); 
    recruiter_sheet.getRange(cellBelow[0],cellBelow[1]).setValue(array[i]); 
    }; 
}; 

回答

1

您需要在函数的顶部定义变量i

function printCalendarValues(array){ 
    var i;//Define i - its' value will be undefined 

或者你需要添加for参数内var关键字。 for (var i = 0, etc现在,变量i是全球性的。 i的值在“全球范围”。 任何你运行的功能将有权访问i,因为它现在是。

当你的第二个for循环调用getCellBelow功能,for环和getCellBelow共享变量i功能两者。因此,i设置为1,然后函数getCellBelow被调用。然后i被设置回零。所以你的for循环将永远持续下去。它永远不会达到1.它通过getCellBelow函数不断被置回零。

for(i=0;i<2;i++){ //i gets set to zero and then incremented to 1 
    var cellBelow = getCellBelow(i+1, Calendar_Display_values);//function called 

然后在函数getCellBelow;

for(i=0; i<rangeArray.length; i++){//i is set to zero and until the array lengh 

因此,i现在可以很容易地大于一。你的循环for(i=0;i<2;i++){将停止。

您可以通过添加Logger.log('i: ' + i)语句,然后查看日志来看到此情况。在查看菜单中,运行代码后选择日志。

你应该定义i功能的内部function getCellBelow(day, rangeArray){

应该是:

function getCellBelow(day, rangeArray){ 
    var i; 

所以,i该函数内部的使用将被限制在功能和不影响i任何其他值在该功能之外。