简体   繁体   中英

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

How to increment my global variable 'currentstep' in Google App Script. The third if statement, I used currentstep++ but it doesn't increase as it stayed at 2. Furthermore, I had tried currentstep += 1; and currentstep = currentstep + 1; Both methods don't work as well.

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;
} 

In google apps script every time you make a function call the global variable get reinitialized. So typically it's better to use PropertiesService or CacheService for global parameters that you wish to change from one execution to another.

The conditions like this:

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

Have little sense. They are equal with this:

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

So your function can be boiled down to this:

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

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

And it works fine by itself, as far as I can tell.

Here is a test:

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

Probably @Cooper is right. You're doing something fancy that we can't know from your question. Are you running the script several times and trying to keep the global value between the runs?

Update

If you suspect that the problem is a global variable you can modify your function to avoid using the global variable within the 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;
}

And call the function this way:

currentstep = check_command(data, currentstep);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM