简体   繁体   English

全局变量未按预期更新

[英]Global variable not updating as expected

I am building a small tool using Apps Script.我正在使用 Apps 脚本构建一个小工具。 I can't seem to get the global variable (URL) to update to include the docId.我似乎无法获取要更新的全局变量 (URL) 以包含 docId。

What I expect我期待什么

  • Run the App function, which first creates a Google Doc and sets the global variable for the documentId (docId).运行 App function,它首先创建一个 Google Doc 并为 documentId (docId) 设置全局变量。 Second it calls myOnClickhandler, which should take the global url variable that includes the updated docId.其次它调用 myOnClickhandler,它应该采用包含更新的 docId 的全局变量 url。

What is happening:怎么了:

  • The variable 'url' in myClickHandler is not updated to the value of 'docId' set in the createProject function. myClickHandler中的变量“url”未更新为在 createProject function 中设置的“docId”值。
var docId = "";
var url = "https://docs.google.com/document/d/" + docId + "/";   
 

function doGet() {
      var output = HtmlService.createHtmlOutputFromFile('MyUI');
      return output;
    }

function createProject(test="test"){
  const doc = DocumentApp.create(test);
  docId = doc.getId();// <-- Update global docId variable. Doesn't seem to be working. 
  Logger.log("Doc ID is: " + docId);
}

function myOnClickHandler(){
  const myList = ["Hello from the server", url]
  Logger.log("URL is: " + url);
}

function app(){
  createProject();
  myOnClickHandler();
}

Probably a simple mistake on my part, but I am banging my head against the wall on this one.对我来说可能是一个简单的错误,但我正在用头撞墙。 Screenshot attached.附上截图。

在此处输入图像描述

In JavaScript, strings are immutable .在 JavaScript 中,字符串是不可变的。 Use an arrow function and a template literal instead of a static text string, like this:使用箭头 function模板文字代替 static 文本字符串,如下所示:

let docId;
const getUrl_ = (docId) => `https://docs.google.com/document/d/${docId}/`;

function test() {
  docId = 'testString';
  const url = getUrl_(docId);
  console.log(url);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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