javascript - Google Apps 脚本挂起 (javascript)

标签 javascript google-apps-script

以下 Javascript 挂起。我一直在自学 Apps 脚本来对工作表上的数据进行排序。在过去的两个小时里,我和我的网络开发人员 friend 一直不明白为什么这个特定的脚本会停止。它只是说永远运行脚本......

发生的情况是,我将电子表格的一部分指定为日历区域,该区域已经由我的其他功能之一打印了动态日历。出于测试目的,我隔离了这个函数并给它一个虚拟数组,但该函数应该循环遍历日历,找到“日期”的坐标,即第 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]);
  }; 
};

最佳答案

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

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

或者您需要添加var for 内的关键字参数。 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 的任何其他值在该函数之外。

关于javascript - Google Apps 脚本挂起 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45112103/

相关文章:

php - 如何在JQuery中选择按钮

google-apps-script - 直到某一天为止?

javascript - 403错误-调用者没有权限

google-apps-script - Google 电子表格/文档,在打开时跳转到当前日期单元格

javascript - 在循环之前完成函数的运行

javascript - 为什么我在使用以下代码时遇到未捕获的类型错误?

javascript - 通过 php 将数据发布到我的 AngularjS 数据库

node.js - 在 Linux 上使用 clasp 时缺少 node-v57-linux-x64-glibc/grpc_node.node

google-apps-script - 使用新的 G Suite Marketplace 流程私下发布 Google 表格插件(无需验证)

php - jquery动态分页评论