正确使用|| [英] Proper use of ||
问题描述
我想的一般问题是:什么时候做?|返回左侧的项目,何时返回右侧的项目?
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 this 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);
}
推荐答案
它返回上的项目当且仅当它是真实的时候离开。
It returns the item on the left if and only if it is truthy.
以下不是真实的:
- 原始布尔值
false
- 原始字符串值
(空字符串)
- 数字+ 0,-0和
NaN
- 原始值
null
- 原始值
undefined
- The primitive boolean value
false
- The primitive string value
""
(the empty string) - the numbers +0, -0 and
NaN
- the primitive value
null
- the primitive value
undefined
其他一切都是真的。
在你的情况下 cache [0]
返回0,我们可以看到它是假的,所以它进入递归。这就是我们在这些情况下避免 ||
短路的原因。
In your case cache[0]
returns 0 which as we can see is falsy so it enters recursion. This is why we avoid ||
for short circuiting in these situations.
你应该考虑直接检查对象有这个属性:缓存中的数字
是这样的,另一个是缓存[数字]!==未定义
。
You should consider checking directly that the object has that property: number in cache
is one such way and another is cache[number] !== undefined
.
这篇关于正确使用||的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!