簡體   English   中英

谷歌應用腳本中全局變量的增量不起作用

[英]Increment of global variable in google app script isn't working

如何在 Google App Script 中增加我的全局變量 'currentstep'。 第三個 if 語句,我使用了 currentstep++,但它沒有增加,因為它保持在 2。此外,我嘗試了 currentstep += 1; 和 currentstep = currentstep + 1; 這兩種方法都不起作用。

function check_command(data){
  var text = data.message.text;
  
  if(text == "/start" || text == "/start"){
    currentstep = 1;
    return;
  }
  
  if (text == "/survey" || text == "/survey"){
    currentstep = 2;
    return;
  }
  if (text){
    currentstep++;
  }
  return;
} 

在谷歌應用程序腳本中,每次您調用 function 時,都會重新初始化全局變量。 因此,通常最好將 PropertiesService 或 CacheService 用於您希望從一個執行更改為另一個執行的全局參數。

像這樣的條件:

if (text == "/start" || text == "/start") { ... }

有點意思。 它們與此相等:

if (text == "/start") { ... }

所以你的 function 可以歸結為:

function check_command(data) {
    var text = data.message.text;

    if (text == "/start")  { currentstep = 1; return }
    if (text == "/survey") { currentstep = 2; return }
    if (text)              { currentstep++ }
}

據我所知,它本身運行良好。

這是一個測試:

 function check_command(data) { var text = data.message.text; if (text == "/start") { currentstep = 1; return } if (text == "/survey") { currentstep = 2; return } if (text) { currentstep++ } } var currentstep = 0; var data = {message: {text: ""}}; var texts = [, "", false, "/start", "/survey", "", , "aaa", "/survey", 123, "/start", "" ] for (let txt of texts) { data.message.text = txt; check_command(data); console.log("currentstep = " + currentstep + " for '" + txt + "'"); }

可能@Cooper 是對的。 您正在做一些我們無法從您的問題中知道的花哨的事情。 您是否多次運行腳本並試圖在運行之間保持全局值?

更新

如果您懷疑問題是全局變量,您可以修改 function 以避免在 function 中使用全局變量:

function check_command(data, counter) {
    var text = data.message.text;

    if (text == "/start")  return = 1;
    if (text == "/survey") return = 2;
    if (text) counter++;

    return counter;
}

並以這種方式調用 function:

currentstep = check_command(data, currentstep);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM