Ric*_*ico 5 javascript recursion
我在下面尝试了递归字符串反转:
function reverse(str){
var results =[];
var j =0;
if(str.length === 0){
console.log('this is zero, yo');
return results.join('');
}
results[j] = str[str.length -1];
console.log('results: ' + results);
j++;
var next = str.substring(0,str.length -1);
console.log(next);
return reverse(next);
}
try{
console.log('***');
console.log(reverse('testing'));
}
catch(e){
console.log('blew the stack');
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,上次函数运行时结果被设置为空字符串。我应该创建一个返回的内部函数results,所以它没有设置为空字符串吗?这段代码接近吗?
编辑:这是为了好奇,我试图不使用使它变得非常简单的功能(反向())
您的代码中的问题是,您每次都省略最后一个字符并在最后一次递归调用中返回空字符串。
相反,获取字符串的最后一个字符并附加字符串其余部分的反转值。
你可以像这样实现它
function reverse(str) {
if (str.length === 0) {
return "";
}
return str[str.length - 1] + reverse(str.substring(0, str.length - 1));
}
Run Code Online (Sandbox Code Playgroud)
在这里,reverse("abc")会这样评价
"c" + reverse("ab")
"c" + ("b" + reverse("a"))
"c" + ("b" + ("a" + reverse(""))) // Hits the `base condition` of recursion
"c" + ("b" + ("a" + "")) // Unwinding begins here
"c" + ("ba")
"cba"
Run Code Online (Sandbox Code Playgroud)