如何将内置的 Javascript 函数编码为递归函数(使用全局变量)



我是JavaScript的新手,并且被困在需要使用递归函数和全局变量的string.replace 程序上。目的是将一个单词/短语(sub_key(的任何实例替换为另一个单词/短语(sub_value(,然后用sub_value填充句子的末尾。

这是我的基本代码:

function Obscure(sub_key, sub_value, sentence) {
  var obscuredSentence = sentence.replace(sub_key, sub_value);
  var obscuredSentence = sub_value + " " + obscuredSentence + " " + sub_value;
  return obscuredSentence;
}
console.log(Obscure("the", "the goat", "I want the money")
    //--> "the goat I want the goat money the goat" );

但是,我需要编写一个运行两次(并且仅运行两次(的递归函数,以便在sub_value也包含sub_key的情况下继续用sub_value替换sub_key(例如"山羊"(。我的最后一句话应该读作"山羊我要山羊钱山羊"。

我尝试了这段代码,但它溢出了堆栈(ha(:

function Obscure(sub_key, sub_value, sentence) {
  var obscuredSentence = sentence.replace(sub_key, sub_value);
  for (var count = 1; count < 2; count++) {
    return Obscure(sub_key, sub_value, sentence);
  }
  var obscuredSentence = sub_value + " " + obscuredSentence + " " + sub_value;
  return obscuredSentence;
}
console.log(Obscure("the", "the goat", "I want the money"));
//"RangeError: Maximum call stack size exceeded (line 2 in function Obscure)"

任何帮助/建议都非常感谢。非常感谢。

我对下面的代码进行了一个小的更改,如果您只想执行两次,它应该可以解决您的问题。

var count = 1;
function Obscure(sub_key, sub_value, sentence) {
  var obscuredSentence = sentence.replace(sub_key, sub_value);
  for (; count < 2;) {
    count++;
    return Obscure(sub_key, sub_value, obscuredSentence);
  }
  var obscuredSentence = sub_value + " " + obscuredSentence + " " + sub_value;
  return obscuredSentence;
}
console.log(Obscure("the", "the goat", "I want the money"));

for(不是

递归的,而是迭代的。

您需要两个函数:一个是带有递归调用的帮助程序函数,另一个是仅负责填充末端和调用递归 fn。

function obscureInside(sub_key, sub_value, sentence, repetitions) {
  if (repetitions <= 0) {
    return sentence;
  }
  var sentenceAfterSingleRun = sentence.replace(sub_key, sub_value);
  return obscureInside(sub_key, sub_value, sentenceAfterSingleRun, repetitions - 1);
}
function obscure(sub_key, sub_value, sentence) {
  var obscuredSentence = obscureInside(sub_key, sub_value, sentence, 2);
  return sub_value + " " + obscuredSentence + " " + sub_value;
}
console.log(obscure("the", "the goat", "I want the money"));

相关内容

  • 没有找到相关文章

最新更新