简体   繁体   中英

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. I've been through several tutorials and based my code on this: 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. 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. 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");}

Rather than execute the function, it's just returning the text. I'm really new to javascript and Google Apps script. Is this a GAS issue or is my code way off? Any help is appreciated.

Thanks.

The changeData function you have is declaring a function and returning the new function.

You just need to return the results of the changeData function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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