首页 > 解决方案 > 想要匹配字符串但得到:TypeError:不能在非对象上使用实例

问题描述

想要匹配字符串但得到:

TypeError:不能在非对象上使用实例

我正在尝试调整以下脚本:

https://rickpastoor.com/2019/05/30/google-calendar-color-coder.html

function ColorEvents() {

  var today = new Date();
  var nextweek = new Date();
  nextweek.setDate(nextweek.getDate() + 7);
  Logger.log(today + " " + nextweek);

  var calendars = CalendarApp.getAllOwnedCalendars();
  Logger.log("found number of calendars: " + calendars.length);

  for (var i=0; i<calendars.length; i++) {
    var calendar = calendars[i];
    var events = calendar.getEvents(today, nextweek);
    for (var j=0; j<events.length; j++) {
      var e = events[j];
      var title = e.getTitle();
      if ("[TEST]" in title[0]) {
        e.setColor(CalendarApp.EventColor.GREY);
      }
      if (title[0] == "!") {
        e.setColor(CalendarApp.EventColor.RED);
      }
      if (title[0] == '#') {
        e.setColor(CalendarApp.EventColor.GREEN);
      }
    }
  }
}

当我尝试运行它时,出现错误:

TypeError:不能在非对象上使用实例。(第 17 行,文件“颜色代码”)

这本质上是“if ("[TEST]" in title[0]) {" 行

如果标题[0] 包含字符串“[TEST]”,我想要一个匹配项

标签: javascript

解决方案


不确定您要达到什么目的,但是您完全滥用了 in 运算符,该运算符应该仅用于对象(并且您的title[0]似乎是一个字符串)。如果您尝试检查您的字符串是否包含其他子字符串,请使用includes()


推荐阅读