我编写了一个简单的javascript程序来执行递归。由于某些原因,它无法正常运行。在递归的一级,当我应该获得cd时,我得到了bcd。
任何帮助将不胜感激。
function recursion_test(i_s) {
console.log('starting string:' + i_s);
if (i_s.length <= 1) {
console.log('base case: ' +i_s);
return
} else {
midPoint = Math.floor(i_s.length /2);
console.log('mid:' + midPoint, 'l: ' + i_s.substring(0,midPoint), ' r: '+ i_s.substring(midPoint, i_s.length));
recursion_test(i_s.substring(0, midPoint));
recursion_test(i_s.substring(midPoint, i_s.length));
}
}
var start_str = "abcd";
console.log("Done: " + recursion_test(start_str));
The starting string:abcd
rec_test:32 mid:2 l: ab r: cd
rec_test:26 starting string:ab
rec_test:32 mid:1 l: a r: b
rec_test:26 starting string:a
rec_test:28 base case: a
rec_test:26 starting string:b
rec_test:28 base case: b
rec_test:26 starting string:bcd
rec_test:32 mid:1 l: b r: cd
rec_test:26 starting string:b
rec_test:28 base case: b
rec_test:26 starting string:cd
rec_test:32 mid:1 l: c r: d
rec_test:26 starting string:c
rec_test:28 base case: c
rec_test:26 starting string:d
rec_test:28 base case: d
rec_test:40 Done: undefinedoutput:
答案 0 :(得分:1)
您应该在let
之前使用midPoint
,否则它将成为全局变量
function recursion_test(i_s) {
console.log('starting string:' + i_s);
if (i_s.length <= 1) {
console.log('base case: ' +i_s);
return
} else {
let midPoint = Math.floor(i_s.length /2);
console.log('mid:' + midPoint, 'l: ' + i_s.substring(0,midPoint), ' r: '+ i_s.substring(midPoint, i_s.length));
recursion_test(i_s.substring(0, midPoint));
recursion_test(i_s.substring(midPoint, i_s.length));
}
}
var start_str = "abcd";
console.log("Done: " + recursion_test(start_str));
答案 1 :(得分:1)
这是因为您定义的变量midPoint
是全局变量。
recursion_test(i_s.substring(0, midPoint));
recursion_test(i_s.substring(midPoint, i_s.length));
上面的第一个recursion_test
会将midPoint
的值更改为1,从而使第二个函数(其中i_s=='abcd'
)以'abcd'.substring(1, 4) -> bcd
作为输入。
要解决此问题,只需在变量var
之前添加midPoint
答案 2 :(得分:0)
function Write(str){
console.log(str);
}
function getData(s,start,end=0){
if (end == 0) {
end = s.length;
}
return s.substring(start, end)
}
function getMidPoint(s) {
var midPoint = Math.floor(s.length / 2);
var left = getData(s,0, midPoint);
var right = getData(s,midPoint);
Write('mid:' + midPoint + ' L: ' + left + ' R: ' + right );
return midPoint;
}
function recursion_test(i_s) {
Write(`Starting String: ` + i_s);
if (i_s.length <= 1) {
Write('base case: ' + i_s);
} else {
let midPoint = getMidPoint(i_s);
let left = getData(i_s,0,midPoint);
let right = getData(i_s,midPoint);
let arr = [left,right];
arr.forEach(function(e) {
recursion_test(e);
});
return "All Done";
}
}
var start_str = "abcd";
Write(recursion_test(start_str));
此解决方案只是对代码进行重构,因此一目了然。另外,请注意,用let
声明的变量仅存在于块范围内。