You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用String.includes()判断函数参数内容时报TypeError的解决咨询

修复includes函数不存在的TypeError

嘿,这个问题我之前也碰到过!你遇到的是环境兼容性问题——includes()是ES6才引入的字符串方法,而你当前的执行环境(比如老版本的Google Apps Script)还不支持它,所以哪怕你把sport转成了字符串,也会抛出找不到函数的错误。

这里有两个简单可靠的修复方案:

方案1:用兼容性更好的indexOf()替代

indexOf()是JavaScript里老牌的字符串查找方法,几乎所有环境都支持。它会返回目标子串的起始索引,找不到就返回-1,我们只要判断返回值不等于-1,就能实现和includes()一样的逻辑:

function addToCalendar(sport, date, time){
  var sportName = String(sport);
  // 用indexOf替代includes,判断是否包含"Soccer"
  Logger.log(sportName.indexOf("Soccer") !== -1);
}

方案2:添加兼容补丁,保留includes()写法

如果你更习惯用includes()的语法,可以在代码最开头加一段兼容补丁,手动给String原型添上这个方法:

// 兼容补丁:如果环境原生不支持includes,就手动实现一个
if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    start = start || 0;
    // 利用indexOf实现includes的逻辑
    return this.indexOf(search, start) !== -1;
  };
}

function addToCalendar(sport, date, time){
  var sportName = String(sport);
  Logger.log(sportName.includes("Soccer"));
}

选其中一个方案修改后,你的代码就能正常判断sport是否包含"Soccer"子串啦。

内容的提问来源于stack exchange,提问作者Lontronix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:49:45