繁体   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