1

我正在尝试为 google docs 电子表格创建自定义函数。我觉得这是一个非常简单的问题,我很快就超出了我的深度。请帮我。一个正确方向的观点将不胜感激。

googledocs 脚本编辑器给出了这个错误:

TypeError: Cannot call method "replace" of undefined. (line 50)

对于此代码:

  function replaceGender(name, gender, comment) {

      var genderedComment = String();
      var name;
      var gender;
      var comment;

      if(gender == "m")
      {
          genderedComment = ungenderedComment.replace("(name)", name).replace(/\(He\/She\)/g,"He").replace(/\(His\/\Her\)/g,"His").replace(/\(his\/\her\)/g,"his").replace(/\(him\/\her\)/g,"him").replace(/\(he\/\she\)/g,"he");
      }
      else
      {   
          genderedComment = ungenderedComment.replace("(name)", name).replace(/\(He\/She\)/g,"She").replace(/\(His\/\Her\)/g,"Her").replace(/\(his\/\her\)/g,"her").replace(/\(him\/\her\)/g,"her").replace(/\(he\/\she\)/g,"she");
      }

      return genderedComment;
};

我认为这很容易,但我做错了什么。

我已经更改了代码,它现在可以正常工作,但是最后一个.replace(/\(he\/\she\)/g,"she");并且.replace(/\(he\/\she\)/g,"he"); 不要替换。??不知道...再次感谢您的所有帮助...正如我所说,我学到了很多东西。

这是现在的代码

function replaceGender(name, gender, comment) {

  if(gender == "m")
  {
    comment = comment.replace(/\(name\)/g, name).replace(/\(He\/She\)/g,"He").replace(/\(His\/\Her\)/g,"His").replace(/\(his\/\her\)/g,"his").replace(/\(him\/\her\)/g,"him").replace(/\(he\/\she\)/g,"he");
  }
  else if(gender == "f")
  {   
    comment = comment.replace(/\(name\)/g, name).replace(/\(He\/She\)/g,"She").replace(/\(His\/\Her\)/g,"Her").replace(/\(his\/\her\)/g,"her").replace(/\(him\/\her\)/g,"her").replace(/\(he\/\she\)/g,"she");
  }

  return comment;
};
4

2 回答 2

1

Several problems actually, aside from the undefined error. You don't want to declare those variables at the top of the function, since what you need is already passed into the function.

function replaceGender(name, gender, comment) {
  var genderedComment;

  if(gender == "m")
  {
  genderedComment = comment.replace("(name)", name).replace(/\(He\/She\)/g,"He").replace(/\(His\/\Her\)/g,"His").replace(/\(his\/\her\)/g,"his").replace(/\(him\/\her\)/g,"him").replace(/\(he\/\she\)/g,"he");
  }
  else
  {   
  genderedComment = comment.replace("(name)", name).replace(/\(He\/She\)/g,"She").replace(/\(His\/\Her\)/g,"Her").replace(/\(his\/\her\)/g,"her").replace(/\(him\/\her\)/g,"her").replace(/\(he\/\she\)/g,"she");
  }

  return genderedComment;
};
于 2013-02-14T02:51:35.360 回答
0

您命名ungenderedComment的变量未定义。


您可以测试以查看变量是否未定义,如下所示:

if (typeof someVariable === 'undefined') {
    alert("variable is undefined");
}

或者像这样:

if (! someVariable) {
    alert("variable is either undefined, null, false, zero, or some falsey value");
}

编辑:正如评论所指出的,看起来您完全使用了错误的变量!

于 2013-02-14T02:45:16.853 回答