TypeError:无法调用undefined的方法“replace”

时间:2013-02-14 02:41:41

标签: javascript types

我正在尝试为Google文档电子表格创建自定义函数。我觉得这是一个非常简单的问题,我很快就离开了我的深度。 请帮我。我们非常感谢正确方向上的一点。

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;
};

2 个答案:

答案 0 :(得分:1)

实际上有几个问题,除了未定义的错误。您不希望在函数顶部声明这些变量,因为您需要的已经传递给函数。

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;
};

答案 1 :(得分:0)

未定义名为ungenderedComment的变量。


您可以测试变量是否未定义如下:

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

或者像这样:

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

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