简体   繁体   English

在Google Apps脚本的for循环内调用函数

[英]Call a function inside a for loop in Google Apps Script

I've found a lot of information about calling functions inside loops but I haven't discovered anything dealing with Google Apps Script. 我发现了很多有关在循环内调用函数的信息,但是我还没有发现任何有关Google Apps脚本的信息。 I've been through several tutorials and based my code on this: http://tobyho.com/2011/11/02/callbacks-in-loops/ . 我已经看过多个教程,并基于此创建了代码: http : //tobyho.com/2011/11/02/callbacks-in-loops/

My real script pulls data from a Fusion Table and puts it in a Google Doc. 我的真实脚本从Fusion Table中提取数据,并将其放入Google文档中。 I'm trying to replace some of the Fusion Table numerical data with actual names, but I need a function to run inside the loop for it to work. 我试图用实际名称替换某些Fusion Table数字数据,但我需要一个函数在循环内运行才能正常工作。 Here's a simplified scenario that is giving me the same issues. 这是一个简化的方案,它给了我同样的问题。

    var big = [];
    var data = [["fname1", "lname1", 2, 1980],["fname2", "lname2", 3, 1989]];

    function loop() {
      for(i in data) {
        Logger.log(big[i] = changeData(data[i][2]));
    }
    }

    function changeData(n) {
      return function() {
        Logger.log(n + "this worked");
      };
    }

When I check the logs I get this twice: function () { Logger.log(n + "this worked");} 当我检查日志时,会得到两次:function(){Logger.log(n +“ this work”);}

Rather than execute the function, it's just returning the text. 而不是执行功能,它只是返回文本。 I'm really new to javascript and Google Apps script. 我真的是JavaScript和Google Apps脚本的新手。 Is this a GAS issue or is my code way off? 这是GAS问题还是我的代码有误? Any help is appreciated. 任何帮助表示赞赏。

Thanks. 谢谢。

The changeData function you have is declaring a function and returning the new function. 您拥有的changeData函数正在声明一个函数并返回新函数。

You just need to return the results of the changeData function 您只需要返回changeData函数的结果

function changeData(n) {      
    Logger.log(n + "this worked"); 
    return "changed data result";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM