0

我正在为 googlespreadsheet 编写一些脚本。其中一项功能需要获得用户输入。之后,我需要在其他一些函数中使用输入,下面显示了一个示例。问题是,每次我需要使用输入时都需要调用函数“Setup()”吗?这将意味着多次要求输入,我知道这很愚蠢。

我该如何解决这个问题?

谢谢!

var setupdone = false;

function Setup(){
  if(!setupdone){
    numofTeams = Browser.inputBox('Confirm the number of Teams');
    var ui = Browser.msgBox('Ensure that the teams are arranged according to lane allocations below', Browser.Buttons.OK_CANCEL);
    setupdone = true;
  }

  var semisraw = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Secondary Group 1');
  var range = semisraw.getDataRange();
  values = range.getValues();
};

function numofTeamsprint(){
  Setup();
  Browser.msgBox('Setup is Complete!');
};
4

3 回答 3

0

您可以设置numofTeams等于-1,然后只要求输入 if numofTeamsis < 0,如下所示:

var numofTeams = -1;

function Setup(){
  if (numofTeams < 0) {
    numofTeams = Browser.inputBox('Confirm the number of Teams');
  }
  var ui = Browser.msgBox('Ensure that the teams are arranged according to lane allocations below', Browser.Buttons.OK_CANCEL);
  var semisraw = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Secondary Group 1');
  var range = semisraw.getDataRange();
  values = range.getValues();
};

function numofTeamsprint(){
  Setup();
  Logger.log(values[0][0]);
};

如果您出于某种原因再次需要该输入,只需将其设置回-1,然后运行Setup()​​。

于 2013-09-27T02:02:31.097 回答
0

如果您将变量定义为全局变量(在函数之外),那么您可以测试它们是否已设置,并且仅提示它们是否尚未设置。

var setupDone = false;

function setup () {
  if (!setupDone) {
    // do whatever
    setupDone = true;
  }

}
于 2013-09-27T02:02:50.243 回答
0

global variable如果变量附加到window对象,则任何变量都称为 a 。

考虑这个例子。

var thisIsAGlobalVar = 4;

function method1() {
    var thisIsALocalVar;

    // My Code
    // 1. thisIsALocalVar is available in this function only
    // 2. Its scope would be destroyed as soon as the function itself goes out of scope
    // 3. thisIsAGlobalVar can be access here.

    //Suppose I introduce another variable, without the var keyword, like the one below, inside of a function, the JavaScript interpretter adds it to the window object

    thisAlsoIsAGlobalVar = "Global";

}

function method2 () {

    //My Code
    // 1. thisIsAGlobalVar can be accessed here also

    //Other Code

    //Now that thisAlsoIsAGlobalVar is declared in method1, it has become global and hence can be used here as well
    //Only Pre-condition being method1 should be called firsr

    console.log(thisAlsoIsAGlobalVar); // Would print "Global"

    console.log(thisIsALocalVar); // Would be "undefined"

}

希望这会有所帮助,干杯!

于 2013-09-27T02:48:37.140 回答