Google函数返回未定义

问题描述 投票:0回答:1

我在使用自定义Google脚本生成一堆包含其他工作表信息的工作表时遇到问题。我不知道为什么会这样。.

我已经尝试在返回值正确之前包括日志和值。但是,当返回时,我得到的值未定义。与函数有关:getTournamentInfo(),从TournamentInfo = getTournamentInfo(matchInfo [0]);

function getTournamentInfo(abbreviation) {
  var sheet = ss.getSheetByName("Tournaments");
  var tournaments = sheet.getRange("B2:B").getValues().filter(String);
  console.log("Fetching Abbreviation: " + abbreviation);
  var r = 2;
  tournaments.forEach(function (tournament) {
    if (tournament != "")
    {
      var tInfo = sheet.getRange("B"+r+":K"+r).getValues().toString().split(",");
      if (tInfo[0] == abbreviation) {
        console.log("Returning Info for: " + tInfo[0]);
        return tInfo;
      }
    }
  });
}

function generateSheets() {
  var sheet = ss.getSheetByName("Match Schedule");
  var matches = sheet.getRange("B5:B").getValues().filter(String);

  var r = 5;
  matches.forEach(function (match) {
    if (match != "")
    {
      var matchInfo = sheet.getRange("B"+r+":L"+r).getValues().toString().split(",");
      if (matchInfo[10] == "true") // Checks wether or not to generate the sheet
      {
        console.log("Generate = " + matchInfo[10]);
        console.log("Fetching Tournament Info: " + matchInfo);
        var tournamentInfo = "";
        try {
          tournamentInfo = getTournamentInfo(matchInfo[0]);
        } catch (e) {
          console.log(e);
        }
        console.log(tournamentInfo);

        var template = "1v1PlayerTemplate"; // Default Template
        if (tournamentInfo[3] == 2) {
          template = "1v1TeamTemplate";
        } else if (tournamentInfo[3] == 3) {
          template = "XvXTeamTaplte";
        }
        var sheetName = matchInfo[0] + " | " + matchInfo[1];
        var matchSheet = ss.getSheetByName(template).copyTo(ss.getSheetByName(template).getParent()).setName(sheetName);

      }
    }
    r++;
  });
}```
javascript
1个回答
0
投票

您的getTournamentInfo函数未返回您的结果。您的return语句仅会使forEach中提供的功能短路。这是可能的解决方案之一(未试用):

function getTournamentInfo(abbreviation) {
    var sheet = ss.getSheetByName("Tournaments");
    var tournaments = sheet.getRange("B2:B").getValues().filter(String);
    console.log("Fetching Abbreviation: " + abbreviation);
    var r = 2;
    let result; // <----
    tournaments.forEach(function (tournament) {
        if (tournament != "" && result == undefined) {
            var tInfo = sheet.getRange("B" + r + ":K" + r).getValues().toString().split(",");
            if (tInfo[0] == abbreviation) {
                console.log("Returning Info for: " + tInfo[0]);
                result = tInfo; // <----
            }
        }
    });
    return result; // <----
}
© www.soinside.com 2019 - 2024. All rights reserved.