2013-09-27 199 views
0

我正在爲googlespreadsheet編寫一些腳本。其中一個功能需要獲取用戶輸入。之後,我需要在一些其他功能中使用輸入,我在下面顯示了一個示例。問題是,每次我需要使用輸入時,是否需要調用函數「Setup()」?這將意味着要求多次輸入,我知道這是愚蠢的。私有/公共變量Javascript

我該如何解決這個問題?

謝謝!

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!'); 
}; 

回答

0

任何變量,如一個可以稱之爲,如果變量被附接到window對象稱爲global variable

考慮一下這個例子。

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" 

} 

希望這會有所幫助,歡呼!

+0

謝謝!這很清楚 – CodeNewbie

0

您可以設置numofTeams等於-1,然後只要求輸入是否numofTeams< 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()

+0

很酷,所以我仍然會調用函數來獲取值。但是由於setupdone檢查,用戶不會被提示。我說得對嗎? – CodeNewbie

+0

是的。你可以多次調用它,只要'numofTeams'小於零,用戶就不會被提示。另一個答案使用相同的概念,但與布爾值。你選擇哪一個取決於你的設計。 – Ben

+0

好的我試過了,它似乎沒有工作。每次運行安裝程序時,它都會提示用戶輸入。編輯的代碼在原始的qn – CodeNewbie

0

如果您將變量定義爲全局變量(函數外部),那麼您可以測試它們是否已設置並且只提示它們是否尚未設置。

var setupDone = false; 

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

} 
+0

很酷,所以,我仍然會調用函數來獲取價值。但是由於setupdone檢查,用戶不會被提示。我說得對嗎?謝謝! – CodeNewbie

+0

好吧我試過了,它似乎沒有工作。每次運行安裝程序時,它仍會提示用戶輸入 – CodeNewbie

+0

也許更新您的問題以顯示您已完成的操作 –