Proper use of ||

前端 未结 3 1139
故里飘歌
故里飘歌 2020-12-03 23:04

The general question I suppose is: when does || return the item on the left, and when does it return the item on the right?

The specific question, is why doesn\'t t

3条回答
  •  感动是毒
    2020-12-03 23:50

    Your code doesn't work because you can't use the value in cache when it's 0 as 0 || func() asks for the function to be called.

    So it always call the second term for 0 and thus makes a stack overflow as the recursion has no end.

    A solution would be to change your internal function like this :

    function fibnonacci(number) {
        if (number in cache) return cache[number];
        return cache[number] = fibnonacci(number - 1) + fibonacci(number - 2);
    }
    

    As an aside please note the spelling of Fibonacci.

提交回复
热议问题