給出一個數字,程序應該返回一個僅使用* 3或+5的操作序列來獲得數字,因此有兩條路徑可以使用。該程序如何知道調用自己時要調用哪個函數?它是如何知道多少次調用每條路徑的。換句話說,我不明白如何使用OR
運營商來確定使用find()
的哪個呼叫以及每個呼叫的數量。OR操作符在這個JavaScript中如何工作?
function findSequence(goal) {
// we start at 1, and history is a string that will keep track of the operations
function find(start, history) {
// case when start and goal is 1.
if (start == goal)
return history; // return string containg 1
// case when we build start past what we needed
else if (start > goal)
return null;
else
// Dont understand this part!
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
document.write(findSequence(13));
在這裏有一個類似的問題http:// stackoverflow。com/questions/2966430/why-does-javascripts-or-return-a-value-other-than-true-false其中有一些有用的信息。 – 2013-03-25 16:39:12