我正在学习 Eloquent JavaScript 的第 3 章,刚刚介绍了递归,我正在尝试围绕这个概念进行思考。
还有人可以解释一下 find 函数中的第二个参数 history 吗?
历史已经被定义了吗?
想一想这个谜题:从数字 1 开始,反复加 5 或乘以 3,可以产生无限多的新数字。你会如何编写一个函数,给定一个数字,试图找到产生该数字的加法和乘法序列?比如13,先乘以3,再加2次5,就可以得到,而15,根本就达不到。
function findSolution(target) {
function find(start, history) {
if (start == target)
return history;
else if (start > target)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
console.log(findSolution(24));
console.log 将打印 findSolution(24) 返回的值,其中 24 是目标。
现在,当函数 findSolution() 被执行时,它调用(调用)带有 2 个参数的函数“find”:start = 1, history = "1"然后返回要打印的内容。
“return”发送回调用设置的地方。这意味着 find() 在 findSolution() 中被调用,因此 return 将发回在 findSolution 中被调用的值。
在我们的例子中:
如果开始===目标
return history //(to findSolution. let's call it "H")
return H to console.log() // prints 1
否则如果开始 > 目标
return null //(to findSolution, let's call it N)
return N to console.log() // prints null
否则如果开始小于目标,
返回一个|| B
A = find(start + 5, "(" + history + " + 5)")
B = find (start * 3, "(" + history + " * 3)")
意思是如果 A 为真则返回 A 否则返回 B;
在函数返回之前评估 A 或 B。
让我们一步一步来:
find 将被一次又一次地调用,start 参数递增 5
即:
return find(1, "1") // start = 1, history = "(1 + 5)"
return find(6, history) // start = 6, history = "(1 + 5 ) + 5"
return find(11, history) // start = 11, history = "(1 + 5) + 5 ) + 5"
return find(16, history) // start = 16, history = "(1 + 5) + 5 ) + 5 ) + 5"
return find(21, history) start = 21, history = "(1 + 5) + 5 ) + 5 ) + 5 ) + 5"
现在下一个值将是 26。因为 26 > 22,“find”将返回 B 而不是
return find(63, history) start = 21 * 3 = 63,
//since 63 > 24, "null" is returned where start = 16,
start 是 16 而不是 63,因为它是一个参数。它没有改变,并且对调用期间发生的 5 递增一无所知。
find(21*3, history) , 48 > 24 所以在 start = 11 处返回 null
find(11 *3, history) , 33 > 24 所以返回 null where start = 6
find(6*3, history) , start = 18 and 18 < 24 所以 A 是真实的 start 将增加 5
返回查找(18 + 5,历史)
return find (23 + 5, history) 28 > 24,A为空,B被求值
... 依此类推,直到 start 等于 24