【问题标题】:Birth Day Reminder on Google Web App Script issue关于 Google Web App 脚本问题的生日提醒
【发布时间】:2020-11-17 14:44:13
【问题描述】:

我正在尝试在 Google 网络应用上显示生日提醒消息,其中数据存储在 Google 表格中。

我在部署的网络应用程序上收到的消息是 --> 今天是 undefined 的生日。

下面是我的脚本代码

function main() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Birthdays");
  var numRows = sheet.getLastRow();
  var range = sheet.getRange(2, 1, numRows - 1, 2).getValues();
  for(var index in range) {
    var row = range[index];
    var name = row[0];
    var birthday = row[1];
    if(isBirthdayToday(birthday)) {
      displayReminder(name);
    }
  }
}

// Check if a person’s birthday is today
function isBirthdayToday(birthday) {
  var today = new Date();
  if((today.getDate() === birthday.getDate()) &&
      (today.getMonth() === birthday.getMonth())) {
    return true;
  } else {
    return false;
    
    console.log(today);
  }
}

// Function to display the reminder
function displayReminder(name) {
  var message = "It is " + name + " 's birthday today.";
  return message;
  console.log(displayReminder);
}

HTML

<div>
<script>
      function onSuccess(quote) {
        var div = document.getElementById('Bday');
        div.innerHTML =  quote;
      }
      google.script.run.withSuccessHandler(onSuccess)
          .displayReminder();
    </script>
   <em> <p id="Bday"></p></em>
</div>

注意:当我为函数 isBirthdayToday(birthday) 运行控制台日志时,出现以下错误。

TypeError:无法读取未定义的属性“getDate”(第 25 行,文件“代码”)

我不知道我哪里出错了。发生了什么错误?

【问题讨论】:

  • 您是否考虑过只为您所有的生日使用日历,然后只需在该日历中查找您的日常活动,然后您就会获得当天的所有生日

标签: javascript google-apps-script google-sheets


【解决方案1】:

答案:

当您使用 for (var index in range) 时,索引不是数组的文字索引 - 它是实际元素本身。

代码修复:

您可以通过不引用rangeindex 元素来解决此问题 - 因为index已经该元素:

var range = sheet.getRange(2, 1, numRows - 1, 2).getValues();
for (var row in range) {
  var name = row[0];
  var birthday = row[1];
  // ...
}

您还从 HTML 中调用了错误的函数:

google.script.run.withSuccessHandler(onSuccess).displayReminder();

应该是:

google.script.run.withSuccessHandler(onSuccess).main();

你还需要从main() 内部返回消息:

function main() {
  // ... code here
  if(isBirthdayToday(birthday)) {
    return displayReminder(name);
  }
}

参考资料:

【讨论】:

  • 我仍然收到相同的未定义名称以及“今天是未定义的生日”这样的消息。
  • 这对我来说没有问题...你还在控制台中得到TypeError: Cannot read property 'getDate' of undefined吗?如果是,第 25 行是什么?
  • if((today.getDate() ===birthday.getDate()) &&
  • getDate() 不是 String 类型的方法,而是 Date 类型的方法。您需要在工作表中设置单元格格式 - 突出显示范围B2:B 并选择Format &gt; Number &gt; More Formats &gt; Custom number format 菜单项,在新打开的模式中键入d/m 并单击Apply。然后尝试运行脚本。
  • 即使在更改格式后我仍然收到错误,这是我正在处理的工作表。您可以复制它以获得更好的洞察力docs.google.com/spreadsheets/d/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多