Proper Use ||

The general question I assume is: when || return an element on the left, and when will it return the element on the right?

The specific question is why this does not work:

var fibonacci = (function () {

    var cache = [0, 1];

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

    return fibonacci;
})();

var $div = $('div');

for (var index = 0; index < 10; index++) {
    $('<span />').text(fibonacci(index))
        .appendTo($div);
}
+3
source share
3 answers

It returns an item on the left if and only if it is right.

The following are not true:

  • The simplest logical value false
  • The value of a primitive string ""(empty string)
  • numbers +0, -0 and NaN
  • primitive meaning null
  • primitive meaning undefined

Everything else is true.

Here is a list of language specifications .

In your case, cache[0]returns 0, which, as we see, is false, so it introduces recursion. That is why we avoid ||short circuits in these situations.

, : number in cache - , - cache[number] !== undefined.

+9

, , 0, 0 || func() .

0 , , , .

, :

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

Fibonacci.

+1

It returns the first trueon the left. If no true, it returns false. If the expressions are allowed to true, in the case of a logical or non-zero or non-zero value or an undefined value.

Edit:

Yes, the meaning must be true ... not only true.

0
source

All Articles