我是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_key
还包含sub_value
(例如“the goat”)的情况下继续用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"));